连接dict值,即列表

nwl*_*wly 9 python dictionary list python-3.x

假设我有以下dict对象:

test = {}
test['tree'] = ['maple', 'evergreen']
test['flower'] = ['sunflower']
test['pets'] = ['dog', 'cat']
Run Code Online (Sandbox Code Playgroud)

现在,如果我跑test['tree'] + test['flower'] + test['pets'],我得到结果:

['maple', 'evergreen', 'sunflower', 'dog', 'cat']
Run Code Online (Sandbox Code Playgroud)

这就是我想要的.

但是,假设我不确定dict对象中有哪些键,但我知道所有值都是列表.有没有像sum(test.values())我这样的方式来实现相同的结果?

jez*_*jez 16

几乎在问题中给出了答案: sum(test.values())只有失败,因为它默认情况下假定您要将项目添加到起始值0- 当然您不能添加listint.但是,如果您明确了起始值,它将起作用:

 sum(test.values(), [])
Run Code Online (Sandbox Code Playgroud)


Psi*_*dom 6

使用chain来自itertools:

>>> from itertools import chain
>>> list(chain.from_iterable(test.values()))
# ['sunflower', 'maple', 'evergreen', 'dog', 'cat']
Run Code Online (Sandbox Code Playgroud)

  • 不确定为什么是downvote,但这也是我的解决方案.另一种选择是`list(chain(*test.values()))` (4认同)

osp*_*hiu 6

一个衬垫(假设不需要特定的订购):

>>> [value for values in test.values() for value in values]
['sunflower', 'maple', 'evergreen', 'dog', 'cat']
Run Code Online (Sandbox Code Playgroud)

  • 我已经使用 python 有一段时间了,有时我会惊讶于列表推导式的不可读性。 (4认同)

Ton*_*has 5

您可以像这样使用functools.reduceand operator.concat(我假设您使用的是 Python 3):

>>> from functools import reduce
>>> from operator import concat
>>> reduce(concat, test.values())
['maple', 'evergreen', 'sunflower', 'dog', 'cat']
Run Code Online (Sandbox Code Playgroud)