問題:每當串列項被三個空串列項分隔時,我想加入串列項。
示例輸入:
input_list = ["hi.", "", "", "", "join me", "", "", "", "hey", "", "", "", "join me too"]
輸出:
output_list = ["hi.join me", "heyjoinmetoo"]
我不知道從哪里開始,但這里有一些我認為可能有用的偽代碼?
- 遍歷串列并檢查串列項是否為空
- 如果它是空的,以某種方式跟蹤有多少空串列項已被迭代。
- 當該數字為 3 時,將前 3 個位置的串列項和下一個項合并在一起。
- 繼續前進,直到沒有 3 個空專案。
這個邏輯有意義嗎?如果是這樣,我將如何開始撰寫這個回圈?
uj5u.com熱心網友回復:
你可以使用這個:
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)
輸出:
['hi.join me', 'heyjoin me too']
uj5u.com熱心網友回復:
只需使用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)
如果這回答了您的問題,您可以勾選此答案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/504627.html
下一篇:如何停止回圈?
