假设我有一个嵌套的字典,如下所示:
numbers = {
'one': {"square": "one", "cube": "one"},
'two': {"square": "four", "cube": "eight"},
'three': {"square": "nine", "cube": "twenty-seven"},
'four': {"square": "sixteen", "cube": "sixty-four"}
}
我想把方块和方块拆成列表。我可以这样做:
squares = [n["square"] for n in numbers.values()]
cubes = [n["cube"] for n in numbers.values()]
但对于重复的代码来说,这似乎不是很令人满意。我也可以引入numpy并这样做:
import numpy
squares_array, cubes_array = numpy.array([(n["square"],n["cube"]) for n in numbers.values()]).T
这很巧妙地将所有东西都打包到numpy数组中,但这看起来有点不令人满意,因为我不需要numpy来做这件事,而且在我高度主观的观点中,在最后进行转置有点奇怪。看起来并不是";蟒蛇;
所以问题是,如果没有numpy,我怎么能在一行中做到这一点?
squares, cubes = zip(*[(n["square"], n["cube"]) for n in numbers.values()])
您可以使用zip
和迭代器:
squares, cubes = map(list, zip(*(d.values() for d in numbers.values())))
如果有更多的密钥或不同的顺序,请手动指定:
squares, cubes = map(list, zip(*([d['square'], d['cube']]
for d in numbers.values())))
输出:
>>> squares
['one', 'four', 'nine', 'sixteen']
>>> cubes
['one', 'eight', 'twenty-seven', 'sixty-four']