Python 从元组列表生成词典列表
我是Python新手。作为一个有趣的练习,我想我应该从元组列表中创建一个字典列表。我一点也不知道我会把头撞在墙上几个小时Python 从元组列表生成词典列表,python,list,dictionary,Python,List,Dictionary,我是Python新手。作为一个有趣的练习,我想我应该从元组列表中创建一个字典列表。我一点也不知道我会把头撞在墙上几个小时 boys = [("Joe", 7, 125), ("Sam", 8, 130), ("Jake", 9, 225)] keys = ("Name","Height","Weight") boyz = [] for x in boys: z = dict(zip(keys,boys[x])) boyz.append(z) print(boyz) 当“boys
boys = [("Joe", 7, 125), ("Sam", 8, 130), ("Jake", 9, 225)]
keys = ("Name","Height","Weight")
boyz = []
for x in boys:
z = dict(zip(keys,boys[x]))
boyz.append(z)
print(boyz)
当“boys[x]”中的x被替换为整数时,效果很好,但在for循环中用变量替换它将不起作用。为什么?我想要一个明确的答案。但是如果有更简洁的方法来写这整件事,请告诉我。在boys循环中的x的
每次迭代中,x
将是列表中下一个元组的值。它不是可以用作索引的整数。在zip
中使用x
而不是boys[x]
,以获得所需的结果
for x in boys:
z = dict(zip(keys,x))
boyz.append(z)
您使用的是boys[x]
而不是x
这会引发错误:
TypeError: list indices must be integers, not tuple
以下是您编辑的代码:
boys = [("Joe", 7, 125), ("Sam", 8, 130), ("Jake", 9, 225)]
keys = ("Name","Height","Weight")
boyz = []
for x in boys:
z = dict(zip(keys,x))
boyz.append(z)
print(boyz)
其运行方式如下:
>>> boys = [("Joe", 7, 125), ("Sam", 8, 130), ("Jake", 9, 225)]
>>> keys = ("Name","Height","Weight")
>>> boyz = []
>>> for x in boys:
... z = dict(zip(keys,x))
... boyz.append(z)
...
>>> print(boyz)
[{'Name': 'Joe', 'Weight': 125, 'Height': 7}, {'Name': 'Sam', 'Weight': 130, 'Height': 8}, {'Name': 'Jake', 'Weight': 225, 'Height': 9}]
>>>
男孩是一张单子。仅列出支持整数索引但要传入元组的索引。您将希望使用x作为元组
最终,您的目标是获得一组键和值以传递给zip
dict(zip(keys, values))
正如您所要求的,可以使用列表理解来实现更简洁的版本
boyz = [dict(zip(keys, boy)) for boy in boys]
通常,当您看到创建空列表、迭代某些iterable并在映射/筛选后追加其值的模式时,您可以使用列表理解
这:
相当于:
new_list = [mapping(item) for item in iterable if condition(item)]
找你什么零钱?错误消息是什么?
new_list = [mapping(item) for item in iterable if condition(item)]