[英]Concatenating dict values, which are lists
假设我有以下 dict 对象:
test = {}
test['tree'] = ['maple', 'evergreen']
test['flower'] = ['sunflower']
test['pets'] = ['dog', 'cat']
现在,如果我运行test['tree'] + test['flower'] + test['pets']
,我会得到结果:
['maple', 'evergreen', 'sunflower', 'dog', 'cat']
这就是我想要的。
但是,假设我不确定 dict 对象中的键是什么,但我知道所有值都是列表。 有没有办法像sum(test.values())
或者我可以运行的东西来达到同样的结果?
您几乎在问题中给出了答案: sum(test.values())
只会失败,因为它默认情况下假定您要将项目添加到起始值为0
— 当然您不能将list
添加到int
。 但是,如果您明确说明起始值,它将起作用:
sum(test.values(), [])
使用来自itertools
chain
:
>>> from itertools import chain
>>> list(chain.from_iterable(test.values()))
# ['sunflower', 'maple', 'evergreen', 'dog', 'cat']
一个班轮(假设不需要特定的订购):
>>> [value for values in test.values() for value in values]
['sunflower', 'maple', 'evergreen', 'dog', 'cat']
您可以像这样使用functools.reduce
和operator.concat
(我假设您使用的是 Python 3):
>>> from functools import reduce
>>> from operator import concat
>>> reduce(concat, test.values())
['maple', 'evergreen', 'sunflower', 'dog', 'cat']
使用numpy.hstack
另一个简单选项:
import numpy as np
>>> np.hstack(list(test.values()))
array(['maple', 'evergreen', 'sunflower', 'dog', 'cat'], dtype='<U9')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.