简体   繁体   English

如何从列表中减去列表中的最小值?

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

I am trying to completely empty the list one by one but there are always 2 integers left. 我正在尝试一张一张地完全清空列表,但总是剩下2个整数。 Is it possible to do it without it leaving the 2 highest value integers ? 是否可以做到这一点而又不留下2个最大值整数? If so how ? 如果可以,怎么办?

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


print(list)

There is an other way to empty a list . 还有另一种清空list This way you don't need to use the for loop. 这样,您就不需要使用for循环。

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

Or: 要么:

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

If you really want to empty the list one element at the time, which doesn't make much sense, you can use a while loop. 如果您真的想一次清空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)
>>> 
[]
>>>

I have a feeling there may be more to your question but to empty a list you can clear it using python3: 我觉得您的问题可能还有更多,但要清空列表,您可以使用python3 清除它:

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

If you actually want each min and have to go one by one keep going until the list is empty: 如果您实际上想要每一分钟并且必须一步一步走,请继续直到列表为空:

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

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

If you want to repeatedly remove the smallest element in this list and process it somehow, instead of just clearing the list, you can do this: 如果要重复删除此列表中的最小元素并以某种方式处理它,而不只是清除列表,可以执行以下操作:

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

(this isn't the most efficient code as it iterates once to find the minimum and again to remove it, but it demonstrates the idea) (这不是最有效的代码,因为它会反复迭代一次以找到最小值,然后再次将其删除,但这证明了这个想法)

Your problem is that you're using a for loop on a list while modifying it which is bound to lead to problems, but there's really no need for a for loop at all. 您的问题是您在修改列表时在列表上使用了for循环,这势必会导致问题,但实际上根本不需要for循环。

Also don't use list as a variable name because it shadows the built-in name which is very useful for other purposes. 也不要使用list作为变量名,因为它会遮盖内置名称,这对于其他目的非常有用。

I think this is what you are trying to do: 我认为这是您想要做的:

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