我有一个清单:
a = [0,1,2,5]
我希望输出类似于:
的输出output = [{'i':0,'v':0},{'i':1,'v':0},{'i':2,'v':0},{'i':5,'v':0}]
使用一行代码/表达式:
output[indx]['i'] = a[indx]
和
output[indx]['v'] = 0
答案 0 :(得分:2)
使用list comprehension生成输出列表:
[{'i': i, 'v': 0} for i in a]
这会产生一个与a
具有相同数量元素的列表,每个字典都有'i'
值设置为a
元素的字典:
>>> a = [0, 1, 2, 5]
>>> [{'i': i, 'v': 0} for i in a]
[{'v': 0, 'i': 0}, {'v': 0, 'i': 1}, {'v': 0, 'i': 2}, {'v': 0, 'i': 5}]