有人能帮我理解下面的代码吗

问题描述

我想了解下面的代码是如何工作的,有人可以帮我解决这个问题吗 看下面的代码

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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...