相关疑难解决方法(0)

Python中的"Zip"列表字典

我有一个列表字典,我想将它们合并到一个namedtuples列表中.我想要第一个元组中所有列表的第一个元素,第二个元素中的第二个元素,依此类推.

例:

{'key1': [1, 2, 3], 'key2': [4, 5, 6], 'key3': [7, 8, 9]}
Run Code Online (Sandbox Code Playgroud)

我希望结果列表如下:

[('key1': 1, 'key2': 4, 'key3': 7), 
('key1': 2, 'key2': 5, 'key3': 8), 
('key1': 3, 'key2': 6, 'key3': 9)]
Run Code Online (Sandbox Code Playgroud)

我假设有一种优雅的方式吗?

编辑:

我已经将@Steve Jessop的namedTuple回答的运行时间与@Ashwini Chaudhary的字典版本进行了比较,前者有点快:

d = {key: numpy.random.random_integers(0, 10000, 100000) 
        for key in ['key1', 'key2', 'key3']}
Run Code Online (Sandbox Code Playgroud)

平均.100次运行:

namedtuple and map: 0.093583753109
namedtuple and zip: 0.119455988407
dictionary and zip: 0.159063346386
Run Code Online (Sandbox Code Playgroud)

python dictionary list

8
推荐指数
2
解决办法
7037
查看次数

标签 统计

dictionary ×1

list ×1

python ×1