a=[0] *10
a[0] ='phase new'
a[3] ='first event'
a[6] ='mid event'
a[9] ='tail event'
我正在寻找一个像python中的简短输出的代码:
['phase new',0,0,'first event',0,0,'mid event',0,0,'tail event']
答案 0 :(得分:1)
您可以在单行中为多个python列表元素赋值,如下所示:
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']
如果您有要替换的值和索引列表,可以使用列表解析来执行此操作:
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)]
答案 1 :(得分:0)
您可以通过使用字典将新值与正确的索引相关联来实现,然后使用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 = map(lambda i: d.get(i, a[i]), range(len(a)))
输出:
['phase new', 0, 0, 'first event', 0, 0, 'mid event', 0, 0, 'tail event']
您也可以使用列表理解代替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)]
输出:
['phase new', 0, 0, 'first event', 0, 0, 'mid event', 0, 0, 'tail event']