问题描述
我想知道一种优雅的Pythonic方法,在Python 3中迭代列表列表(或列表的列表)并行。列表的数量在运行时是不知道的,所以我相信我不能简单地将它们作为参数提供给 zip()
函数。
I'd like to know an elegant, Pythonic way to iterate over a list of lists (or dict of lists) in parallel in Python 3. The number of lists is not known until runtime, so I believe I cannot simply supply them as arguments to the zip()
function.
例如,给定以下数据结构:
For example, given the following data structure:
var = [['x1','x2','x3'],['y1','y2' ,'y3'],['z1','z2','z3'],...]
我想要在每次迭代中访问以下值:
I would like to be able to access the following values on each iteration:
x1,y1,z1
后跟 x2,y2,z2
后跟 x3,y3,z3
等等。
可能我可以直接使用列表索引来实现,或者使用itertools.chain,但是我正在使用生成器或其他方式寻找更优雅的方法。
Presumably I could achieve this using list indexes directly, or by using itertools.chain, but I'm looking for a more elegant approach using generators or otherwise.
推荐答案
zip(* var)
将自动解压缩列表列表。
zip(*var)
will automatically unpack your list of lists.
所以,例如:
var = [['x1' ,'x2' ,'x3'], ['y1', 'y2', 'y3'], ['z1', 'z2', 'z3'], ['w1', 'w2', 'w3']]
for ltrs in zip(*var):
print(", ".join(ltrs))
结果
x1, y1, z1, w1
x2, y2, z2, w2
x3, y3, z3, w3
编辑:,他想使用字典中的项目,
per comments below, he wants to use the items from a dictionary,
var = {
'id_172': ['x1', 'x2', 'x3'],
'id_182': ['y1', 'y2', 'y3'],
'id_197': ['z1', 'z2', 'z3']
}
正在使用按照排序顺序的键值:
I assume we are using the values with the keys in sorted order:
keys = sorted(var.keys())
for ltrs in zip(*(var[k] for k in keys)):
print(", ".join(ltrs))
其中
x1, y1, z1
x2, y2, z2
x3, y3, z3
警告:请注意,按照排序顺序对字符串进行排序(即字符串字母顺序),例如id_93来自id_101。如果您的标签需要按数字顺序排序,您将需要使用自定义键功能,如
Warning: do note that this sorts the keys in lexocographic order (ie string alphabetical order), so for example "id_93" comes after "id_101". If your labels need to be sorted in numeric order you will need to use a custom key function, something like
keys = sorted(var.keys(), key=lambda k: int(k[3:]))
这篇关于多个列表中的并行迭代迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!