python - Python:如何使用列表中的步骤索引更新字典
问题描述
我是一个一周大的 Python 学习者。我想知道:假设:
list= [“a”, “A”, “b”, “B”, “c”, “C”]
我需要在字典中更新它们以获得如下结果:
dict={“a”:”A”, “b”:”B”, “c”:”C”}
我尝试在dict.update({list[n::2]: list[n+1::2]}
and中使用列表索引for n in range(0,(len(list)/2))
我想我做错了什么。请纠正我。
先感谢您。
解决方案
尝试以下操作:
>>> lst = ['a', 'A', 'b', 'B', 'c', 'C']
>>> dct = dict(zip(lst[::2],lst[1::2]))
>>> dct
{'a': 'A', 'b': 'B', 'c': 'C'}
说明:
>>> lst[::2]
['a', 'b', 'c']
>>> lst[1::2]
['A', 'B', 'C']
>>> zip(lst[::2], lst[1::2])
# this actually gives a zip iterator which contains:
# [('a', 'A'), ('b', 'B'), ('c', 'C')]
>>> dict(zip(lst[::2], lst[1::2]))
# here each tuple is interpreted as key value pair, so finally you get:
{'a': 'A', 'b': 'B', 'c': 'C'}
注意:不要将变量命名为与 python 关键字相同的名称。
您的程序的正确版本是:
lst = ['a', 'A', 'b', 'B', 'c', 'C']
dct = {}
for n in range(0,int(len(lst)/2)):
dct.update({lst[n]: lst[n+1]})
print(dct)
您的不起作用,因为您在每次迭代中都使用了切片,而不是访问每个单独的元素。lst[0::2]
给['a', 'b', 'c']
和lst[1::2]
给['A', 'B', 'C']
。因此,对于第一次迭代,当n == 0
您尝试使用该对更新字典时['a', 'b', 'c'] : ['A', 'B', 'C']
,您将收到类型错误,因为list
无法将其分配为字典的键,因为list
s 是不可散列的。
推荐阅读
- objective-c - UITextView 中的可点击链接将导航到另一个控制器
- jquery - 猫头鹰旋转木马在多个项目上带有动画
- arrays - 如何使用 ADODB 与 EXCEL 文件连接的记录集将 Excel 工作表中的数据加载到二维数组中?
- java - 将参数传递给杰克逊中的getter
- html - 是否在 SharePoint 中翻译了 aria-labels
- c# - 返回具有泛型类型的类的函数,以返回具有特定类型的类
- python - 如何在烧瓶应用程序中将 ID 列显示为路由超链接?
- uwp - 如何在 UWP 更新安装上启动 fullTrustProcess exe?
- c# - 如何使wpf文件激活?
- matplotlib - Matplotlib:使用 TRISURF 的 GRID 和 COLORMAP