Python 用于非预定义列表计数的itertools.izip()
我有以下数据结构:Python 用于非预定义列表计数的itertools.izip(),python,itertools,Python,Itertools,我有以下数据结构:{'one':['a','b','c'],'two':['q','w','e'],'three':['t','u','y'],…}。因此,字典有不同的键数。由dict键拾取的每个数组具有相似的长度。如何将此结构转换为以下内容:[{'one':'a','two':'q','three':'t},{'one':'b','two':'w','three':'y'},] 我想我应该使用itertools.izip(),但是如何在没有预定义参数计数的情况下应用它呢?可能是这样的:iter
{'one':['a','b','c'],'two':['q','w','e'],'three':['t','u','y'],…}
。因此,字典有不同的键数。由dict键拾取的每个数组具有相似的长度。如何将此结构转换为以下内容:[{'one':'a','two':'q','three':'t},{'one':'b','two':'w','three':'y'},]
我想我应该使用itertools.izip(),但是如何在没有预定义参数计数的情况下应用它呢?可能是这样的:itertools.izip([data[l]表示data.keys()中的l)
蒂亚 不太优雅,但有个窍门:
In [9]: [{k:v[i] for (k,v) in d.items()} for i in range(len(d.values()[0]))]
Out[9]:
[{'one': 'a', 'three': 't', 'two': 'q'},
{'one': 'b', 'three': 'u', 'two': 'w'},
{'one': 'c', 'three': 'y', 'two': 'e'}]
我忍不住想,一定有更好的方法来表达I
循环,但现在我什么都没想到
或者:
In [50]: map(dict, zip(*[[(k, v) for v in l] for k, l in d.items()]))
Out[50]:
[{'one': 'a', 'three': 't', 'two': 'q'},
{'one': 'b', 'three': 'u', 'two': 'w'},
{'one': 'c', 'three': 'y', 'two': 'e'}]
不过,不确定这是否在可读性方面有很大的改进。您在使用方面的评估是正确的,但使用方法不太正确
你首先需要
- 以元组(键、值)列表的形式获取项,(如果使用Py2.x,则使用
方法;如果使用Py3.x,则使用iterms()
)items()
- 创建键和值的标量乘积
- 展平列表(使用itertools.chain)
- 压缩它(使用itertools.izip)
- 然后创建每个元素的dict
>>> from pprint import PrettyPrinter
>>> pp = PrettyPrinter(indent = 4)
>>> pp.pprint(map(dict, izip(*chain((product([k], v) for k, v in data.items())))))
[ { 'one': 'a', 'three': 't', 'two': 'q'},
{ 'one': 'b', 'three': 'u', 'two': 'w'},
{ 'one': 'c', 'three': 'y', 'two': 'e'}]
>>>
next(iter(d.values())
是另一种选择。还是很丑。