[英]fatest way to mix two lists in python
我們有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需要稍微不同的roundrobin
版本,在2.x文檔中提供 。
這也避免了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:]
這不是一個簡短的方法,但它消除了不必要的依賴。
更新:這是@jsvk建議的另一種方式
mixed = []
for i in range( len(min(l1, l2)) ):
mixed.append(l1[i])
mixed.append(l2[i])
list += max(l1, l2)[i+1:]
如果您需要單個列表中的輸出,而不是元組列表,請嘗試此操作。
Out=[]
[(Out.extend(i) for i in (itertools.izip_longest(l1,l2))]
Out=filter(None, Out)
我並不認為這是最好的方法,但我只想指出可以使用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']
>>> 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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.