How to iterate through two lists in parallel?
我在python中有两个iterables,我想成对检查它们:
1 2 3 4 5 | foo = (1, 2, 3) bar = (4, 5, 6) for (f, b) in some_iterator(foo, bar): print"f:", f,"; b:", b |
这将导致:
1 2 3 | f: 1; b: 4 f: 2; b: 5 f: 3; b: 6 |
一种方法是迭代索引:
1 2 | for i in xrange(len(foo)): print"f:", foo[i],"; b:", b[i] |
但对我来说,这似乎有点不合时宜。有更好的方法吗?
1 2 | for f, b in zip(foo, bar): print(f, b) |
当
在python 2中,
1 2 3 4 5 | 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) |
当
在python 3中,
还要注意,
1 2 3 | for num, cheese, color in zip([1,2,3], ['manchego', 'stilton', 'brie'], ['red', 'blue', 'green']): print('{} {} {}'.format(num, color, cheese)) |
印刷品
1 2 3 | 1 red manchego 2 blue stilton 3 green brie |
您需要
1 2 | for (f,b) in zip(foo, bar): print"f:", f ,"; b:", b |
内置的
你要找的叫
您应该使用"zip"功能。下面是一个示例,说明您自己的zip函数的外观
1 2 3 4 5 | def custom_zip(seq1, seq2): it1 = iter(seq1) it2 = iter(seq2) while True: yield next(it1), next(it2) |
Zip函数解决了这个问题docs:zip库函数
目标:将输出并排放置问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 | #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" " for val2 in value2: print(val2.text) print" " |
输出:回顾1回顾2回顾三DATE1DATE2数据3
解决方案:
1 2 3 4 | for val1, val2 in zip(value1,value2): print (val1.text+':'+val2.text) print" " |
输出:ReVIEW1:DATE1ReVIEW2: DATE2ReVIEW3:DATE3
您可以在一本词典中使用3种类型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | def construct_dictionary_from_lists(names, ages, scores): end_str_dic = {} for item_name, item_age, score_item in zip(names, ages, scores): end_str_dic[item_name] = item_age, score_item return end_str_dic print( construct_dictionary_from_lists( ["paul","saul","steve","chimpy"], [28, 59, 22, 5], [59, 85, 55, 60] ) ) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 |