列表具有相同數量的元素,並且名稱是唯一的。 我想知道,我如何在一個動作中做出一個字典。通過遍歷兩個列表(列表解析)來製作一個列表的列表
這是我當前的代碼:
fees = [fee for fee in fees]
names = [name for name in names]
mdict = [
{'fees': fee[i], 'names': names[i]}
for i, val in enumerate(fees)]
列表具有相同數量的元素,並且名稱是唯一的。 我想知道,我如何在一個動作中做出一個字典。通過遍歷兩個列表(列表解析)來製作一個列表的列表
這是我當前的代碼:
fees = [fee for fee in fees]
names = [name for name in names]
mdict = [
{'fees': fee[i], 'names': names[i]}
for i, val in enumerate(fees)]
您可以使用這兩個列表zip
在列表理解:
mdict = [{'fees': f, 'names': n} for f, n in zip(fees, names)]
非常感謝你。工作正常 – Leo
試試這個:
result = dict(zip(fees, names))
你的意思是壓縮?
dict(zip(fees, names))
你要這個
{fees[i]:y[i] for i in range(len(fees))}
或相當多:
dict(zip(fees, names))
使用zip()或zip_longest() –
[將兩個列表映射到Python中的字典中](http://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in- python) – RvdK
在前兩行賦值之前有什麼類型的對象是「收費」和「名稱」? – Matt07