2016-03-24 47 views
0

我想完全清空列表中的一个,但总是有2个整数左。 有没有可能离开2个最高值的整数?如果是这样如何?如何从列表中减去列表中的最小值?

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


print(list) 
+0

如果你想使用'for'循环清空列表,你应该这样做相反的方式。检查[this](http://stackoverflow.com/questions/35618307/how-to-transform-string-into-dict/35618686#35618686)否则,您的索引器将在通过所有项目之前到达列表的末尾。在索引器向前移动时,以前向方式进行操作将删除列表中的项目。它可能会扰乱迭代流程。这就是说,使用for循环不是清空列表的唯一方法 – Ian

回答

0

还有一种方法可以清空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) 
>>> 
[] 
>>> 
+0

或'lst [:] = []' –

+0

@PeterWood是的,我将编辑我的文章 –

0

我有一种感觉,可能会有更多你的问题,但清空列表您可以明确它使用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) 
0

如果要重复删除此列表中的最小元素并以某种方式处理它,而不是只是cl抽穗列表,你可以这样做:

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

(这是不是最有效的代码,因为它一次迭代找到最小,并再次将其删除,但它表明了想法)

你问题在于你在修改列表时使用了for循环,这会导致问题,但是根本不需要for循环。

也不要使用list作为变量名称,因为它会隐藏内置名称,这对于其他目的非常有用。

0

我想这是你正在尝试做的:

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)