下面的代码一次只能访问一个列表,并且每个循环向前看 1 个元素:
from itertools import izip_longest
alist = ['foo','bar','duh']
blist = ['ofo','ardavak','dot','dotdat']
for i, plus1 in izip_longest(alist, alist[1:], fillvalue=None):
iplus1 = i + plus1 if plus1 is not None else ""
for j, plus1 in izip_longest(blist, blist[1:], fillvalue=None):
jplus1 = j + plus1 if plus1 is not None else ""
我如何同时展望 2 个列表的每个循环的 1 个元素?就像是:
for (i,plus1),(j,plus1) in izip(izip_longest(alist, alist[1:], fillvalue=None), izip_longest(blist, blist[1:], fillvalue=None)):
print i,j
print i,j+plus1
print i+plus1,j
print i+plus1,j+plus1
所需的输出应如下所示:
foo ofo
foo ofoardavak
foobar ofo
foobar ofoardvak
bar ardavak
bar ardavakdot
barduh ardavak
barduh ardavakdot
duh dot
duh dotdotdat
dot
dotdotdat
dotdat
dotdat