8

2つのリストを用意しましょう

l1 = [1, 2, 3]
l2 = [a, b, c, d, e, f, g...]

結果:

list = [1, a, 2, b, 3, c, d, e, f, g...] 

zip()結果を最小に短縮するため使用できませんlistlist出力には ではなくも必要iterableです。

4

7 に答える 7

10
>>> l1 = [1,2,3]
>>> l2 = ['a','b','c','d','e','f','g']
>>> [i for i in itertools.chain(*itertools.izip_longest(l1,l2)) if i is not None]
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']

リストに値を含めることができるNoneようにするには、次の変更を使用できます。

>>> from itertools import chain, izip_longest
>>> l1 = [1, None, 2, 3]
>>> l2 = ['a','b','c','d','e','f','g']
>>> sentinel = object()
>>> [i
     for i in chain(*izip_longest(l1, l2, fillvalue=sentinel))
     if i is not sentinel]
[1, 'a', None, 'b', 2, 'c', 3, 'd', 'e', 'f', 'g']
于 2012-09-29T01:46:57.220 に答える
7

別の可能性...

[y for x in izip_longest(l1, l2) for y in x if y is not None]

(もちろん、itertools から izip_longest をインポートした後)

于 2012-09-29T01:50:27.497 に答える
2

これを行う最も簡単な方法は、itertoolsドキュメントに記載されているラウンド ロビン レシピを使用することです。

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

次のように使用できます。

>>> l1 = [1,2,3]
>>> l2 = ["a", "b", "c", "d", "e", "f", "g"]
>>> list(roundrobin(l1, l2))
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']

2.x には、2.x ドキュメントroundrobinで提供されている、わずかに異なるバージョンの が必要であることに注意してください。

これにより、リストが削除されずにzip_longest()リストに含まれる可能性があるというメソッドの問題も回避されます。None

于 2012-09-29T02:21:24.387 に答える
1
minLen = len(l1) if len(l1) < len(l2) else len(l2)
for i in range(0, minLen):
  list[2*i] = l1[i]
  list[2*i+1] = l2[i]
list[i*2+2:] = l1[i+1:] if len(l1) > len(l2) else l2[i+1:]

this is not a short way but it removes unnecessary dependencies.

update: here is another way that was suggested by @jsvk

mixed = []
for i in range( len(min(l1, l2)) ):
  mixed.append(l1[i])
  mixed.append(l2[i])
list += max(l1, l2)[i+1:]
于 2012-09-29T01:57:14.010 に答える
0

これが最善の方法であるとは言いませんが、zip を使用できることを指摘したかっただけです。

b = zip(l1, l2)
a = []
[a.extend(i) for i in b]
a.extend(max([l1, l2], key=len)[len(b):])

>>> a
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']
于 2012-09-29T02:12:33.973 に答える
0

タプルのリストではなく、単一のリストで出力が必要な場合は、これを試してください。

Out=[]
[(Out.extend(i) for i in (itertools.izip_longest(l1,l2))]
Out=filter(None, Out)
于 2012-09-29T01:56:54.920 に答える
0
>>> a = [1, 2, 3]
>>> b = list("abcdefg")
>>> [x for e in zip(a, b) for x in e] + b[len(a):]
[1, 'a', 2, 'b', 3, 'c', 'd', 'e', 'f', 'g']
于 2012-09-29T02:59:18.893 に答える