python-3.x - 如何使用for循环遍历两个列表来创建字典
问题描述
我有两个列表:
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}
谁能解释我在哪里做错了??
解决方案
您正在使用嵌套的 for 循环。对于每个i
inname_list
和每个j
in num_list
,您都在 dictionary 中添加一个元素new
。因此,最后,您将 4*4 = 16, key, value 对添加到字典中。
你可以这样做:
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]
推荐阅读
- java - 如何在谷歌云端点框架 v2 的每种方法中重用连接池?
- python - 递归……我卡住了
- apache-kafka - 如何在 Kafka 中实现时间序列汇总?
- html - 填充 SVG 的内部区域
- python - 无法在 torchtext 迭代器中加载 one-hot 标签(ValueError: too many dimensions 'str')
- caching - 具有 sql 缓存依赖的内存缓存
- sql - 选择具有特定条件的最新行
- java - 如何调试 Quarkus/SmallRye 客户端请求
- python - Django:在 JSONField 上使用 F() 表达式?
- vb.net - 有没有更好的方法来写这个。尝试某事直到 3 次或成功