[python] 如何并行迭代两个列表?


Answers

你想要的zip功能。

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

我在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]

但是这对我来说似乎有些不和谐。 有没有更好的方法来做到这一点?




你在找什么叫做zip




zip函数解决了这个问题
文档: zip

AIM:并排输出问题:

#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




Related