将列表理解转换为功能编程
我有每个字典中每个键的字典列表
lst = [{'a': (1, 2, 3), 'b': (2, 3)},
{'c': (3, 6), 'd': (4, 8), 'e': (5, 10)},
{'d': (6, 12), 'e': (7, 14)}]
,我只想保留值的第一个元素。因此,所需的输出是
[{'a': 1, 'b': 2}, {'c': 3, 'd': 4, 'e': 5}, {'d': 6, 'e': 7}]
我可以使用列表理解的列表来获得它
[{key: val[0] for key, val in dct.items()} for dct in lst]
,但是我想知道是否可以使用地图,ItemGetter,Itertools,functools等获得相同的输出。到目前为止,我所拥有的内容:
map(dict.values, lst)
但是我不知道如何从这里去。
I have a list of dictionaries
lst = [{'a': (1, 2, 3), 'b': (2, 3)},
{'c': (3, 6), 'd': (4, 8), 'e': (5, 10)},
{'d': (6, 12), 'e': (7, 14)}]
For each key in each dictionary, I want to keep only the first element of the values. So the desired output is
[{'a': 1, 'b': 2}, {'c': 3, 'd': 4, 'e': 5}, {'d': 6, 'e': 7}]
I can get it using a list comprehension like
[{key: val[0] for key, val in dct.items()} for dct in lst]
However, I want to know if it's possible to get the same output using map, itemgetter, itertools, functools etc. What I have so far:
map(dict.values, lst)
But I don't know how to go from here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于嵌套的迭代,我认为没有Lambda表达的帮助,我们无法做到:
我不得不说这很丑陋。
更新:
我找到了一种避免lambda的方法:
dict
>可以在Lambda外移动。我们只需要添加另一个MAP
:Zip
外部lambda:d.Values
在lambda之外。在这里,由于确定了列表的元素类型,因此我们直接使用dict.values
而不是operator.methodcaller
:functools.partial
:测试:
For nested iterations, I don't think we can do it without the help of lambda expressions:
I have to say it's very ugly.
Update:
I found a way to avoid lambda:
dict
can be moved outside lambda. We just need to add anothermap
:zip
outside lambda:d.values
outside lambda. Here, since the element type of the list is determined, we directly usedict.values
instead ofoperator.methodcaller
:functools.partial
:Test: