簡體   English   中英

如何在每個其他元素處組合兩個字符串列表?

[英]How do I combine two lists of strings at every other element?

我將如何從

lst1 = ['the', 'brown', 'jumps', 'the', 'dog']
lst2 = ['quick', 'fox', 'over', 'lazy']

到這個輸出:

['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

沒有定義新功能?

到目前為止,我已經嘗試過:

insertcounter = 1
for k in lst2:
    lst1.insert(insertcounter, k)
    insertcounter += 1

但它只是在第一個索引處插入整個 lst2 而不是循環。 我確信答案顯而易見,但我是菜鳥,它並沒有打動我。

提前致謝!

insertcounter += 1更改為insertcounter += 2

只是為了好玩,我會這樣嘗試:

它與roundrobin類似,但可能更快:它產生與 roundrobin() 相同的輸出,但對於某些輸入可能表現更好(特別是當可迭代的數量很大時)。 如果interables很小,它很可能。 不過會有很大的不同。

為了完全誠實地使用這個庫,您必須首先通過執行pip install more_itertools來安裝它。 感謝@Matiiss 提醒。

>>> from more_itertools import interleave_longest
>>> list(interleave_longest(lst1, lst2))
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
>>> 

您可以遍歷較長列表的范圍並根據需要捕獲 IndexError 異常:

lst1 = ['the', 'brown', 'jumps', 'the', 'dog']
lst2 = ['quick', 'fox', 'over', 'lazy']
out = []
for i in range(len(lst1)):
    try:
        out.append(lst1[i])
        out.append(lst2[i])
    except IndexError:
        continue

print(out)

結果:

['敏捷的棕色狐狸跳過了懶狗']

即使列表的長度不同,您也可以使用itertools.zip_longest一起迭代列表:

import itertools

output = []
for i,j in itertools.zip_longest(lst1, lst2):
   output.append(i)
   if j:
       output.append(j)
print(output) 
lst1 = ['the', 'brown', 'jumps', 'the', 'dog',"murat"]
lst2 = ['quick', 'fox', 'over', 'lazy',"ali"]

newList=[]

if(len(lst1)>len(lst2)):
    for i in range(len(lst1)):
        newList.append(lst1[i])
        if(len(lst2)>i):
            newList.append(lst2[i])
else:
    for i in range(len(lst2)):
        newList.append(lst2[i])
        if(len(lst1)>i):
            newList.append(lst1[i])

print(newList)

你可以使用rangezip來做到這一點:

lst1 = ['the', 'brown', 'jumps', 'the', 'dog']
lst2 = ['quick', 'fox', 'over', 'lazy']

for i, word in zip(range(1, len(lst2)*2, 2), lst2):
    lst1.insert(i, word)

print(lst1)
# ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

TIO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM