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()
結果を最小に短縮するため使用できませんlist
。list
出力には ではなくも必要iterable
です。
>>> 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']
別の可能性...
[y for x in izip_longest(l1, l2) for y in x if y is not None]
(もちろん、itertools から izip_longest をインポートした後)
これを行う最も簡単な方法は、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
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:]
これが最善の方法であるとは言いませんが、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']
タプルのリストではなく、単一のリストで出力が必要な場合は、これを試してください。
Out=[]
[(Out.extend(i) for i in (itertools.izip_longest(l1,l2))]
Out=filter(None, Out)
>>> 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']