簡體   English   中英

如果列表大於 1,如何從列表中刪除項目?

[英]how to remove an item from a list if the list is greater than 1?

我有一個列表,我希望列表只有一項,怎么做? 我試過這樣做,但它給了我一個錯誤: ValueError: list.remove(x): x not in list這是代碼:

List = ["dairy"]
List.append("cheese")

if len(List) > 1:
    List.remove(1)

Python 的.remove() 方法將您要刪除的值作為其參數,因此它正在尋找列表中的數字 1。 要按索引刪除,可以使用 del or.pop()。 例如:

l  = ['dairy']
l.append('cheese')

if len(l) > 1:
     l.pop() # Removes last item in list

暫無
暫無

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

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