1

下面的代码一次只能访问一个列表,并且每个循环向前看 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
4

2 回答 2

1

也许是这样的:

from itertools import izip_longest

alist = ['foo','bar','duh']
blist = ['ofo','ardavak','dot','dotdat']

combined_list = list(izip_longest(alist, blist, fillvalue=""))

for (i,j),(iplus1,jplus1) in izip_longest(combined_list, combined_list[1:], fillvalue=("", "")):
    print i,j
    print i,j+jplus1
    print i+iplus1,j
    print i+iplus1,j+jplus1

但请注意 zip() 只接受min(len(alist),len(blist))元素,即返回的列表在长度上被截断为最短参数序列的长度。

于 2013-01-08T06:49:01.617 回答
1
from itertools import product,izip,izip_longest

def pairs(lst):
    i = iter(lst)
    prev = i.next()
    for item in i:
        yield prev, prev+item   
        prev = item

[list(product(*v)) for v in izip(*map(pairs,
                   izip(*izip_longest(alist,blist,fillvalue=''))))]

出去:

[[('foo', 'ofo'),
  ('foo', 'ofoardavak'),
  ('foobar', 'ofo'),
  ('foobar', 'ofoardavak')],
 [('bar', 'ardavak'),
  ('bar', 'ardavakdot'),
  ('barduh', 'ardavak'),
  ('barduh', 'ardavakdot')],
 [('duh', 'dot'), ('duh', 'dotdotdat'), ('duh', 'dot'), ('duh', 'dotdotdat')]]
于 2013-01-08T08:02:39.200 回答