首页 文章

如何并行迭代两个列表?

提问于
浏览
600

我在Python中有两个迭代,我想成对地遍历它们:

foo = (1, 2, 3)
bar = (4, 5, 6)

for (f, b) in some_iterator(foo, bar):
    print "f: ", f, "; b: ", b

它应该导致:

f: 1; b: 4
f: 2; b: 5
f: 3; b: 6

一种方法是迭代索引:

for i in xrange(len(foo)):
    print "f: ", foo[i], "; b: ", b[i]

但这对我来说似乎有点不合时宜 . 有没有更好的方法呢?

7 回答

  • 45
    for f, b in zip(foo, bar):
        print(f, b)
    

    foobar 中的较短者停止时 zip 停止 .

    Python 2 中,zip返回元组列表 . 当 foobar 不大时,这很好 . 如果它们都是大规模的那么形成 zip(foo,bar) 是一个不必要的大量临时变量,应该被 itertools.izipitertools.izip_longest 替换,它返回迭代器而不是列表 .

    import itertools
    for f,b in itertools.izip(foo,bar):
        print(f,b)
    for f,b in itertools.izip_longest(foo,bar):
        print(f,b)
    

    foobar 用尽时 izip 停止 . 当 foobar 都用完时 izip_longest 停止 . 当较短的迭代器耗尽时, izip_longest 会在与该迭代器对应的位置产生一个 None 的元组 . 如果您愿意,还可以在 None 之外设置不同的 fillvalue . 请参阅此处查看full story .

    Python 3 中,zip返回元组的迭代器,如Python2中的 itertools.izip . 要获取元组列表,请使用 list(zip(foo, bar)) . 并且要压缩直到两个迭代器都耗尽,你将使用itertools.zip_longest .


    还要注意 zip 及其 zip -like brethen可以接受任意数量的iterables作为参数 . 例如,

    for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], 
                                  ['red', 'blue', 'green']):
        print('{} {} {}'.format(num, color, cheese))
    

    版画

    1 red manchego
    2 blue stilton
    3 green brie
    
  • 14

    你想要 zip 功能 .

    for (f,b) in zip(foo, bar):
        print "f: ", f ,"; b: ", b
    
  • 960

    内置 zip 完全符合您的要求 . 如果你想要相同的迭代而不是列表,你可以看看itertools.izip,它做同样的事情,但一次给出一个结果 .

  • 6

    您正在寻找的是zip .

  • 4

    你应该使用'zip'功能 . 以下是您自己的zip功能的示例

    def custom_zip(seq1, seq2):
        it1 = iter(seq1)
        it2 = iter(seq2)
        while True:
            yield next(it1), next(it2)
    
  • -3

    zip功能解决了这个问题
    文件:ZIP Library function

    目的:并排输出问题:

    #value1 is a list
    value1 = driver.find_elements_by_class_name("review-text")
    #value2 is a list
    value2 = driver.find_elements_by_class_name("review-date")
    
    for val1 in value1:
        print(val1.text)
        print "\n"
    for val2 in value2:
        print(val2.text)
        print "\n"
    

    输出:
    review1
    review2
    review3
    DATE1
    DATE2
    DATE3

    解:

    for val1, val2 in zip(value1,value2):
        print (val1.text+':'+val2.text)
        print "\n"
    

    输出:
    review1:DATE1
    review2:DATE2
    review3:DATE3

  • 11
    def ncustom_zip(seq1,seq2,max_length):
            length= len(seq1) if len(seq1)>len(seq2) else len(seq2) if max_length else len(seq1) if len(seq1)<len(seq2) else len(seq2)
            for i in range(length):
                    x= seq1[i] if len(seq1)>i else None  
                    y= seq2[i] if len(seq2)>i else None
                    yield x,y
    
    
    l=[12,2,3,9]
    p=[89,8,92,5,7]
    
    for i,j in ncustom_zip(l,p,True):
            print i,j
    for i,j in ncustom_zip(l,p,False):
            print i,j
    

相关问题