from itertools import zip_longest colors=['red','apple','three'] num=[1,2,3,4,5] for i in zip_longest(colors,num): print (i) ''' output: ('red', 1) ('apple', 2) ('three', 3) (none, 4) (none, 5) '''
示例2:
指定fillvalue。
from itertools import zip_longest colors=['red','apple','three'] num=[1,2,3,4,5] for i in zip_longest(colors,num,fillvalue='z'): print (i) ''' output: ('red', 1) ('apple', 2) ('three', 3) ('z', 4) ('z', 5) '''
4. 使用sorted()函数按已排序的顺序循环序列:
sorted():
从iterable中的项返回一个新的排序列表。
示例:1
使用sorted()函数按排序(升序)遍历序列(list)。
num=[10,5,20,25,30,40,35] for i in sorted(num): print (i) ''' output: 5 10 20 25 30 35 40 '''
示例2:
使用sorted()函数按排序(降序)遍历序列(list)。
num=[10,5,20,25,30,40,35] for i in sorted(num,reverse=true): print (i) ''' output: 40 35 30 25 20 10 5 '''
示例3:
使用sorted()函数按排序(升序)遍历字典。默认情况下,它将对字典中的键进行排序。
d={'f':1,'b':4,'a':3,'e':9,'c':2} for i in sorted(d.items()): print (i) #output: ('a', 3) ('b', 4) ('c', 2) ('e', 9) ('f', 1)
示例4:
使用已排序的函数按已排序的顺序循环字典。在已排序的函数中使用key参数,根据字典的值对其排序。
d={'f':1,'b':4,'a':3,'e':9,'c':2} #sorting by values in the dictionary for i in sorted(d.items(),key=lambda item:item[1]): print (i) #output: ('f', 1) ('c', 2) ('a', 3) ('b', 4) ('e', 9)