[英]How can I merge items in a list based on a rule that involves multiple list items in python?
問題:每當列表項被三個空列表項分隔時,我想加入列表項。
示例輸入:
input_list = ["hi.", "", "", "", "join me", "", "", "", "hey", "", "", "", "join me too"]
Output:
output_list = ["hi.join me", "heyjoinmetoo"]
我不知道從哪里開始,但這里有一些我認為可能有用的偽代碼?
這個邏輯有意義嗎? 如果是這樣,我將如何開始編寫這個循環?
你可以使用這個:
list = ["hi.", "", "", "", "join me", "", "", "", "hey", "", "", "", "join me too"]
ind =0
new_list = []
while(ind+4<len(list)):
if list[ind]!="" and list[ind+1:ind+4]==["","",""]:
new_list.append(list[ind]+list[ind+4])
ind+=4
ind+=1
print(new_list)
Output:
['hi.join me', 'heyjoin me too']
只需使用string.join(list)
。 這是代碼:
input_list = ["hi.", "", "", "", "join me", "", "", "", "hey", "", "", "", "join me too"]
output_list = []
ls = []
for i in input_list:
print(ls)
ls.append(i)
if i == "join me" or i == "join me too":
output_list.append("".join(ls))
ls.clear()
print(output_list)
如果這回答了您的問題,您可以勾選此答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.