Python 3.x 如何使用for通过两个列表循环创建字典

Python 3.x 如何使用for通过两个列表循环创建字典,python-3.x,dictionary,Python 3.x,Dictionary,我有两份清单: num_list=[1,2,3,4] name\u list=[“一”、“二”、“三”、“四”] 我想创建一个新字典,将name\u list作为键,将num\u list作为值。 我知道zip方法,但我尝试使用for循环进行学习。我尝试的是: new={} num_list = [1,2,3,4] name_list = ["one","two","three","four"] for i in (name_list): for j in (num_list):

我有两份清单:

num_list=[1,2,3,4]

name\u list=[“一”、“二”、“三”、“四”]

我想创建一个新字典,将
name\u list
作为键,将
num\u list
作为值。 我知道zip方法,但我尝试使用
for
循环进行学习。我尝试的是:

new={}
num_list = [1,2,3,4]
name_list = ["one","two","three","four"]
for i in (name_list):
    for j in (num_list):
        new[i]=j
将输出获取为:

{'one':4,'two':4,'three':4,'four':4}


有人能解释一下我在哪里犯了错误吗???

您正在使用嵌套for循环。 对于
name\u列表中的每个
i
,以及
num\u列表中的每个
j
,您将在dictionary
new
中添加一个元素。最后,您将4*4=16,键,值对添加到字典中

您可以这样做:

new={}
num_list = [1,2,3,4]
name_list = ["one","two","three","four"]
for i in range(len(name_list)):
    new[name_list[i]]=num_list[i]

这个问题类似于在第二个for循环中对每个键迭代num_列表中的所有值,因为每个键都有num_列表中的最后一个值(4)

您只需执行以下操作:

num_list = [1,2,3,4]
name_list = ["one","two","three","four"]

print (dict([[y,num_list[x]] for x,y in enumerate(name_list)]))
输出:

{'one': 1, 'two': 2, 'three': 3, 'four': 4}
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
或:

输出:

{'one': 1, 'two': 2, 'three': 3, 'four': 4}
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
如果要使用您的代码:

new={}
num_list = [1,2,3,4]
name_list = ["one","two","three","four"]
for i in (name_list):
    for j in (num_list):
        new[i]=j
        num_list.remove(j) # <-----
        break # <-----

print (new)

注意:您缺少两行代码

要了解错误,我们必须试运行您的代码。让我们做吧,我复制粘贴你的原始代码在这里。否则你必须滚动屏幕

new={}
num_list=[1,2,3,4]
姓名列表=[“一”、“二”、“三”、“四”]
对于i in(姓名列表):
对于j in(数量列表):
新[i]=j
试运行

+-----+-----+-------------+
|i | j | new[i]=j|
+-----+-----+-------------+
|一| 1 |{'1':1}|
---------------------------
|| 2 |{'one':2}|
---------------------------
|| 3 |{'one':3}|
---------------------------
|| 4 |{'one':4}|
---------------------------
我只在完成第一轮时才进行试跑。所以你的第二个for循环,循环4次。第四次结束时,您的
j
值始终
4
。这就是为什么字典中的所有值都变成了
4
。我能建议一些简单的步骤吗?您的
num\u列表
name\u列表
都是
4
。如果你想试试这个

范围(4)内的i的
:
新的[name_list[i]]=num_list[i]
打印(新)
#或者使用听写理解
打印({(名称列表[i]):(数量列表[i]),用于范围(4)中的i)
输出:

{'one':1,'two':2,'three':3,'four':4}

当您调用第二个for循环时,您正在遍历整个
num\u列表
,因此在代码执行后,
name\u列表
中的每个值都会被指定为具有
num\u列表
最后一个元素的键值对,在这种情况下,
4
可能重复您可以检查此答案@ncica感谢您解释我代码中的错误:)