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- 当然您不能添加list到int.但是,如果您明确了起始值,它将起作用:
sum(test.values(), [])
Run Code Online (Sandbox Code Playgroud)
使用chain来自itertools:
>>> from itertools import chain
>>> list(chain.from_iterable(test.values()))
# ['sunflower', 'maple', 'evergreen', 'dog', 'cat']
Run Code Online (Sandbox Code Playgroud)
一个衬垫(假设不需要特定的订购):
>>> [value for values in test.values() for value in values]
['sunflower', 'maple', 'evergreen', 'dog', 'cat']
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用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)
| 归档时间: |
|
| 查看次数: |
9063 次 |
| 最近记录: |