簡體   English   中英

如何合並列表的某些部分:Python

[英]How to club certain parts of list: Python

我有一個字符串示例清單:

my_list = ['hello','this','is','a','sample','list', 'thanks', 'for', 'help']

我想將每三個元素結合在一起,例如:

new_list = ['hello this is', 'a sample list', 'thanks for help']

只需分成幾大塊並加入:

[' '.join(my_list[i:i+3]) for i in range(0, len(my_list), 3)]

選項1:如果my_list長度不能被3整除,則此解決方案刪除元素

輸入字符串: ['hello','this','is','a','sample','list', 'thanks', 'for', 'help', 'foo']

[" ".join(i) for i in zip(*[iter(my_list)]*3)]

結果: ['hello this is', 'a sample list', 'thanks for help']

python iter技巧的工作原理: zip(* [iter(s)] * n)在Python中如何工作?

選項2:使用zip_longest保留其他元素

輸入字符串: ['hello','this','is','a','sample','list', 'thanks', 'for', 'help', 'foo']

[" ".join(i) for i in zip_longest(*[iter(my_list)]*3, fillvalue='')]

結果: ['hello this is', 'a sample list', 'thanks for help', 'foo ']

您可以通過使用一個步驟(在本例中為3個步驟)進行迭代並在每個步驟下添加單個字符串(即my_list[i]my_list[i+1] my_list[i+2 ] 請注意,您需要在每個第一個和第二個字符串之后添加一個空格。 這段代碼做到了:

new_list = []
for i in range(0, len(my_list), 3):
    if i + 2 < len(my_list):
        new_list.append(my_list[i] + ' ' + my_list[i+1] + ' ' + my_list[i+2])
print(new_list)

輸出是預期的:

['hello this is', 'a sample list', 'thanks for help']

使用itertools幾種解決方案是可能的。

使用groupby

[' '.join(x[1] for x in g) for _, g in groupby(enumerate(my_list), lambda x: x[0] // 3)]

使用teezip_longest

a, b = tee(my_list)
next(b)
b, c = tee(b)
next(c)
[' '.join(items) for items in zip_longest(a, b, c, fillvalue='')]

僅使用zip_longest

[' '.join(g) for g in zip_longest(*[iter(my_list)] * 3, fillvalue='')]

最后兩個改編自文檔中的pairwisegrouper 配方 如果不是三個字的倍數,則只有第一個選項不會在最后一組的末尾添加額外的空格。

暫無
暫無

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

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