简体   繁体   English

从列表中删除最小的 int

[英]Remove smallest int from a list

I want to remove all the "1" from this list, but it keeps always the last one.我想从这个列表中删除所有的“1”,但它总是保留最后一个。 Any help?有什么帮助吗? Thanks!谢谢!

userlist = [1, 1, 1, 2, 1, 4, 1, 5, 1]

smallnumber = min(userlist)
[userlist.remove(x) for x in userlist if x == smallnumber] 

print(userlist)

A more elegant solution would be:一个更优雅的解决方案是:

userlist_new = [x for x in userlist if x != min(userlist)]

There is some answer for this, but you need to see where your wrong:对此有一些答案,但你需要看看你的错误在哪里:

[userlist.remove(x) for x in userlist if x == smallnumber] 

you are using list.remove inside a list comprahention, this is as writing this:您正在列表中使用 list.remove ,这是写这个:

new_list = []
for x in userlist:
   if x == smallnumber:
       new_list.append(userlist.remove(x))

as you can see list.remove return nothing, so the new_list will be full with None , and the userlist will be cleared from the number如您所见, list.remove 什么都不返回,因此list.remove将被None new_list ,并且用户userlist将从数字中清除

I will add another solution:我将添加另一个解决方案:

list(filter((smallnumber ).__ne__, userlist))

[userlist.remove(x) for x in userlist if x == smallnumber]

This line in your code is equivalent to below.您的代码中的这一行相当于下面的代码。 * note the print(x) I have added to show you the point * 请注意我添加的print(x)以向您展示这一点

for x in userlist:
    print(x)
    if x == smallnumber:
        userlist.remove(x)

The problem here is that you are trying to iterate through an object and at the same time removing the object from the list.这里的问题是您试图遍历 object 并同时从列表中删除 object。 This messes up the way python iterates through the loop.这弄乱了 python 遍历循环的方式。 From above print you can see that python won't be traversing all the elements because of this.从上面的打印中,您可以看到 python 不会因此遍历所有元素。

So you should probably use some other logic.所以你可能应该使用其他一些逻辑。 Few has already been suggested in the other answers.其他答案中已经很少有人提出建议。 One another way is to use filters另一种方法是使用过滤器

filtered_list = list(filter(lambda x: x!=smallnumber, userlist))

If you want to change the orginal one itself.如果你想改变原来的本身。 You can use below logic您可以使用以下逻辑

for _ in range(userlist.count(smallnumber)):
    userlist.remove(smallnumber)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM