连接dict值,即列表

2024-05-16 06:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下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())的方法,或者我可以运行一些东西来获得相同的结果?


Tags: 对象方法testtree列表dictcatvalues
3条回答

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

 sum(test.values(), [])

一行代码(假定不需要特定的顺序):

>>> [value for values in test.values() for value in values]
['sunflower', 'maple', 'evergreen', 'dog', 'cat']

使用chain来自itertools

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

相关问题 更多 >