以下代码:
spices={
'Animals':{1:'Bison', 2:'Panther', 3:'Elephant'},
'Birds':{1:'Duck', 2:'Hawk', 3:'Pigeon'},
'Fish':{1:'Shark', 2:'Salmon', 3:'Piranha'}
}
result=[spices[specie].values() for specie in spices]
print result
结果列表:
[['Shark', 'Salmon', 'Piranha'], ['Bison', 'Panther', 'Elephant'], ['Duck', 'Hawk', 'Pigeon']]
但我的目标是获得一个简单的列表,例如:
['Shark', 'Salmon', 'Piranha', 'Bison', 'Panther', 'Elephant', 'Duck', 'Hawk', 'Pigeon']
如何实现这一目标?
答案 0 :(得分:4)
在列表推导中添加循环;嵌套循环从左到右运行:
[v for specie in spices for v in spices[specie].values()]
演示:
>>> spices={
... 'Animals':{1:'Bison', 2:'Panther', 3:'Elephant'},
... 'Birds':{1:'Duck', 2:'Hawk', 3:'Pigeon'},
... 'Fish':{1:'Shark', 2:'Salmon', 3:'Piranha'}
... }
>>> [v for specie in spices for v in spices[specie].values()]
['Shark', 'Salmon', 'Piranha', 'Bison', 'Panther', 'Elephant', 'Duck', 'Hawk', 'Pigeon']
答案 1 :(得分:1)
提到另一种方法:
print reduce(lambda x, y: x + y, map(lambda x: x.values(), spices.values()))
输出:
['Shark', 'Salmon', 'Piranha', 'Bison', 'Panther', 'Elephant', 'Duck', 'Hawk', 'Pigeon']
解释(从右到左):
values
。values
和自定义map
功能提取每个嵌套词典的lambda
。reduce
和另一个自定义lambda
功能连接所有值。答案 2 :(得分:0)
您可以使用itertools.chain
from itertools import chain
spices={
'Animals':{1:'Bison', 2:'Panther', 3:'Elephant'},
'Birds':{1:'Duck', 2:'Hawk', 3:'Pigeon'},
'Fish':{1:'Shark', 2:'Salmon', 3:'Piranha'}
}
print list(chain.from_iterable(spices[specie].values() for specie in spices))
['Shark', 'Salmon', 'Piranha', 'Bison', 'Panther', 'Elephant', 'Duck', 'Hawk', 'Pigeon']