我有两个列表:
num_list = [1,2,3,4]
name_list = ["one","two","three","four"]
我想创建一个新字典,以name_list
作为键,以num_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}
谁能解释我在哪里做错了?
答案 0 :(得分:1)
您正在使用嵌套的for循环。
对于i
中的每个name_list
和j
中的每个num_list
,您要在字典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]
答案 1 :(得分:0)
在第二个for循环中,您要遍历num_list中的所有值的每个键,因为对于每个键,您有num_list中的最后一个值(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}
或:
num_list = [1,2,3,4]
name_list = ["one","two","three","four"]
print ({name_list[i]:num_list[i] for i in range(len(num_list))})
输出:
{'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)
输出:
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
注意:您缺少两行代码
答案 2 :(得分:0)
要了解该错误,我们必须对您的代码进行空运行。做吧,我将您的原始代码复制粘贴到此处。否则,您必须滚动屏幕。
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
试运行
+-----+-----+-------------+
| i | j | new[i]=j |
+-----+-----+-------------+
| one | 1 | {'one':1} |
---------------------------
| | 2 | {'one':2} |
---------------------------
| | 3 | {'one':3} |
---------------------------
| | 4 | {'one':4} |
---------------------------
我只为完成第一轮而进行试跑。因此,您的2 for循环,循环4次。 j
的值总是4
的第4次结束。这就是字典中所有值都变为4
的原因。我可以建议一些简单的步骤吗?您的num_list
和name_list
的长度均为4
。因此,如果需要,请尝试此操作。
for i in range(4):
new[name_list[i]] = num_list[i]
print(new)
# or using dict comprehension
print({(name_list[i]): (num_list[i]) for i in range(4)})
输出:
{'one': 1, 'two': 2, 'three': 3, 'four': 4}