Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表中删除最小的int_Python_List_Integer_Remove - Fatal编程技术网

Python 从列表中删除最小的int

Python 从列表中删除最小的int,python,list,integer,remove,Python,List,Integer,Remove,我想从列表中删除所有“1”,但它始终保留最后一个。有什么帮助吗? 谢谢 更优雅的解决方案是: userlist\u new=[x代表userlist中的x,如果x!=min(userlist)] 对此有一些答案,但您需要了解您的错误: [userlist.remove(x) for x in userlist if x == smallnumber] 您正在列表压缩中使用list.remove,如下所示: new_list=[] 对于用户列表中的x: 如果x==smallnumber: ne

我想从列表中删除所有“1”,但它始终保留最后一个。有什么帮助吗? 谢谢


更优雅的解决方案是:

userlist\u new=[x代表userlist中的x,如果x!=min(userlist)]

对此有一些答案,但您需要了解您的错误:

[userlist.remove(x) for x in userlist if x == smallnumber] 
您正在列表压缩中使用list.remove,如下所示:

new_list=[]
对于用户列表中的x:
如果x==smallnumber:
new_list.append(userlist.remove(x))
正如您所看到的
list.remove
不返回任何内容,因此
new_list
将充满
None
,并且
userlist
将从数字中清除

我将添加另一个解决方案:

list(过滤器((smallnumber)。\uu u ne\u uu,用户列表))
[用户列表。如果x==smallnumber,则删除用户列表中x的(x)]

代码中的这一行相当于以下内容。*请注意我添加的打印(x)以向您展示这一点

for x in userlist:
    print(x)
    if x == smallnumber:
        userlist.remove(x)
这里的问题是,您试图遍历一个对象,同时从列表中删除该对象。这打乱了python在循环中迭代的方式。从上面的图片中,您可以看到python不会遍历所有元素,因为这一点

因此,您可能应该使用其他逻辑。在其他答案中已经很少有人提出。另一种方法是使用过滤器

filtered_list = list(filter(lambda x: x!=smallnumber, userlist))
如果你想改变原来的一个。您可以使用下面的逻辑

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

这回答了你的问题吗?无论如何,最好是
[x代表userlist中的x,如果x!=smallnumber]
最好将最小的数字存储在变量中,以避免为每个值调用
min()。
for _ in range(userlist.count(smallnumber)):
    userlist.remove(smallnumber)