Python |同时迭代多个列表

迭代单个列表,指使用 for循环 对于在特定步骤对单个列表的单个元素进行迭代,而在同时对多个列表进行迭代时,我们使用 for循环 用于在特定步骤对多个列表中的单个元素进行迭代。

null

图片[1]-Python |同时迭代多个列表-yiteyi-C++库

一次迭代多个列表

为了更好地理解多个列表的迭代,我们一次迭代3个列表。

我们可以通过以下方式同时迭代列表:

  1. zip() :在Python 3中,zip返回一个迭代器。当所有列表中的任何一个都用尽时,zip()函数停止。简单地说,它一直运行到所有列表中最小的一个。

    下面是zip函数和itertools的实现。izip迭代3个列表:

    Python3

    # Python program to iterate
    # over 3 lists using zip function
    import itertools
    num = [ 1 , 2 , 3 ]
    color = [ 'red' , 'while' , 'black' ]
    value = [ 255 , 256 ]
    # iterates over 3 lists and executes
    # 2 times as len(value)= 2 which is the
    # minimum among all the three
    for (a, b, c) in zip (num, color, value):
    print (a, b, c)

    
    

    输出:

    1 red 255
    2 while 256
    

  2. itertools。zip_最长() :zip_当所有列表用尽时,最长停止。当较短的迭代器耗尽时,zip_longest将生成一个无值的元组。

    下面是itertools的一个实现。zip_最长,可在3个列表中循环:

    Python3

    # Python program to iterate
    # over 3 lists using itertools.zip_longest
    import itertools
    num = [ 1 , 2 , 3 ]
    color = [ 'red' , 'while' , 'black' ]
    value = [ 255 , 256 ]
    # iterates over 3 lists and till all are exhausted
    for (a, b, c) in itertools.zip_longest(num, color, value):
    print (a, b, c)

    
    

    输出:

    1 red 255
    2 while 256
    3 black None
    

    输出:

    1 red 255
    2 while 256
    3 black None
    

我们还可以在zip_longest()中指定默认值,而不是无

Python3

# Python program to iterate
# over 3 lists using itertools.zip_longest
import itertools
num = [ 1 , 2 , 3 ]
color = [ 'red' , 'while' , 'black' ]
value = [ 255 , 256 ]
# Specifying default value as -1
for (a, b, c) in itertools.zip_longest(num, color, value, fillvalue = - 1 ):
print (a, b, c)


输出:

1 red 255
2 while 256
3 black -1

注: Python 2。x有两个额外的函数izip()和izip_longest()。在Python 2中。x、 zip()和zip_longest()用于返回列表,izip()和izip_longest()用于返回迭代器。在Python 3中。x、 这里没有izip()和izip_longest(),因为zip()和zip_longest()返回迭代器。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享