问题描述
我想了解下面的代码是如何工作的,有人可以帮我解决这个问题吗 看下面的代码
keys = ['name','age','food'] values = ['Monty',42,'spam']
dict = {}
for index,item in enumerate(keys):
dict[item] = values[index]
解决方法
keys = ['name','age','food']
values = ['Monty',42,'spam']
d = {}
for key,value in zip(keys,values):
d[key] = value
print (d)
输出:
{'name': 'Monty','age': 42,'food': 'spam'}
您的代码示例确实非常复杂。此 zip()
方法生成列表列表(嵌套列表)。
要评论您的代码:
keys = ['name','spam']
dic = {}
#index is common to keys and values lists,item is the element at index for keys list
for index,item in enumerate(keys):
#You set the key item with the element found at the corresponding index in values
dic[item] = values[index]
,
for
循环的每次迭代都会创建字典 dict
的一个元素,键为 item
,值为 values
,索引为 index
>