繁体   English   中英

从元组列表中创建字典列表

[英]Making a list of dictionaries from a list of tuples

我是一个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 [x]”中的x被整数替换时,它的效果很好,但是用for循环中的变量替换它将不起作用。 为什么?? 我特别喜欢这个答案。 但是如果有更简洁的方法来写这整篇文章,请告诉我。

for x in boys循环中for x in boys每次迭代中, 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并在map / filtering之后附加其值时,您可以使用列表推导。

这个:

new_list = []
for item in iterable:
    if condition(item):
        new_value = mapping(item)
        new_list.append(new_value)

相当于:

new_list = [mapping(item) for item in iterable if condition(item)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM