list1 = ["apple", "pear", "", "strawberry", "orange", "grapes", "", "watermelon"]
list2 = []
x = 0
while x < len(list1):
if len(list1[x]) > 0:
list2.append(list1[x])
print(list2)
我試圖運行這段代碼,但它似乎不起作用。我應該如何通過不使用串列理解或其他方法來修改此代碼?
uj5u.com熱心網友回復:
更新:只注意到你不希望使用不同的方法,所以這個答案僅僅是為了未來的訪客。
您可以在一行中實作相同的功能:
list2 = list(filter(None, list1))
請注意,這也將洗掉等于元素0,False或None。更接近的實作可能是串列理解:
list2 = [i for i in list1 if i != ""]
uj5u.com熱心網友回復:
更新:因為你說(How should I revise this code by not using list comprehension or other methods?)我發送了這個答案,否則其他答案對未來更好。
您需要在代碼中增加索引,x =1如下所示:
list1 = ["apple", "pear", "", "strawberry", "orange", "grapes", "", "watermelon"]
list2 = []
x = 0
while x < len(list1):
if len(list1[x]) > 0:
list2.append(list1[x])
x = 1
print(list2)
輸出:
['apple', 'pear', 'strawberry', 'orange', 'grapes', 'watermelon']
uj5u.com熱心網友回復:
假設這是您想要的輸出:
['apple', 'pear', 'strawberry', 'orange', 'grapes', 'watermelon']
這是一種不使用內置函式或串列推導式的方法:
list1 = ["apple", "pear", "", "strawberry", "orange", "grapes", "", "watermelon"]
list2 = []
for x in list1:
x and list2.append(x)
假設允許使用內置函式,例如filter:
list1 = ["apple", "pear", "", "strawberry", "orange", "grapes", "", "watermelon"]
list2 = list(filter(None, list1))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/356543.html
上一篇:我可以使用str.append創建一個沒有元音的新字串嗎?
下一篇:C#輸入整數和字符一行
