簡體   English   中英

如何從列表中減去列表中的最小值?

[英]How to subtract from a list by the smallest value in the list?

我正在嘗試一張一張地完全清空列表,但總是剩下2個整數。 是否可以做到這一點而又不留下2個最大值整數? 如果可以,怎么辦?

list = [1,2,3,4,5]
print (list)
for x in list:
    while x in list:
        list.remove(min(list))


print(list)

還有另一種清空list 這樣,您就不需要使用for循環。

>>> lst = [1,2,3,4,5]
>>> del lst[:]
>>> lst
[]
>>> 

要么:

>>> lst = [1,2,3,4,5]
>>> lst[:] = []
>>> lst
[]
>>>

如果您真的想一次清空list一個元素,這沒有多大意義,則可以使用while循環。

lst = [1,2,3,4,5]
x = len(lst)-1
c = 0
while c < x:
    for i in lst:
        lst.remove(i)
    c = c+1
print (lst)
>>> 
[]
>>>

我覺得您的問題可能還有更多,但要清空列表,您可以使用python3 清除它:

lst = [1,2,3,4,5]
lst.clear()

如果您實際上想要每一分鍾並且必須一步一步走,請繼續直到列表為空:

lst = [1, 2, 3, 4, 5]

while lst:
    i = min(lst)
    lst.remove(i)
    print(i, lst)

如果要重復刪除此列表中的最小元素並以某種方式處理它,而不只是清除列表,可以執行以下操作:

while list:  # short way of saying 'while the list is not empty'
    value = min(list)
    process(value)
    list.remove(value)

(這不是最有效的代碼,因為它會反復迭代一次以找到最小值,然后再次將其刪除,但這證明了這個想法)

您的問題是您在修改列表時在列表上使用了for循環,這勢必會導致問題,但實際上根本不需要for循環。

也不要使用list作為變量名,因為它會遮蓋內置名稱,這對於其他目的非常有用。

我認為這是您想要做的:

lst = [1,2,3,4,5] 
while lst:          # while the list is not empty
   m = min(lst)
   while m in lst: # remove smallest element (multiple times if it occurs more than once)
       lst.remove(m)

暫無
暫無

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

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