a=[0] *10
a[0] ='phase new'
a[3] ='first event'
a[6] ='mid event'
a[9] ='tail event'
I am looking for a code that outputs like in a short in python:
['phase new',0,0,'first event',0,0,'mid event',0,0,'tail event']
You can assign values to multiple python list elements in single line like this:
a=[0]*10
a[0], a[3], a[6], a[9] = 'phase new', 'first event', 'mid event', 'tail event'
>>> a
['phase new', 0, 0, 'first event', 0, 0, 'mid event', 0, 0, 'tail event']
In case you've a list of values and indices to replace, you can do it using list comprehension:
indices = [0,3,6,9]
vals = ['phase new', 'first event', 'mid event', 'tail event']
a = [vals[indices.index(i)] if i in indices else 0 for i in range(10)]
You can achieve that by using a dictionary to associate the new value to the right index, and then use map to get what you want:
a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
d = {0: 'phase new', 3: 'first event', 6: 'mid event', 9: 'tail event'}
a = map(lambda i: d.get(i, a[i]), range(len(a)))
Output:
['phase new', 0, 0, 'first event', 0, 0, 'mid event', 0, 0, 'tail event']
You can also achieve the same using list comprehension instead of map:
a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
d = {0: 'phase new', 3: 'first event', 6: 'mid event', 9: 'tail event'}
a = [d.get(i, v) for i,v in enumerate(a)]
Output:
['phase new', 0, 0, 'first event', 0, 0, 'mid event', 0, 0, 'tail event']