Python:从数字列表中删除负数

问题描述:

问题是要消除数字中的负数.

The question is to remove negatives from numbers.

当执行remove_negs([1, 2, 3, -3, 6, -1, -3, 1])时,结果为:[1, 2, 3, 6, -3, 1].结果假定为[1, 2, 3, 6, 3, 1].发生的情况是,如果连续有两个负数(例如-1, -3),则第二个数将不会被删除. def main(): 数字=输入(输入数字列表:") remove_negs(numbers)

When remove_negs([1, 2, 3, -3, 6, -1, -3, 1]) is executed, the result is: [1, 2, 3, 6, -3, 1]. The result is suppose to be [1, 2, 3, 6, 3, 1]. what is happening is that if there are two negative numbers in a row (e.g., -1, -3) then the second number will not get removed. def main(): numbers = input("Enter a list of numbers: ") remove_negs(numbers)

def remove_negs(num_list): 
  '''Remove the negative numbers from the list num_list.'''
    for item in num_list: 
        if item < 0: 
           num_list.remove(item) 

    print num_list

main()

在迭代列表时从列表中删除元素通常是个坏主意(请参阅列表理解:>

It's generally a bad idea to remove elements from a list while iterating over it (see the link in my comment for an explanation as to why this is so). A better approach would be to use a list comprehension:

num_list = [item for item in num_list if item >= 0]

请注意,以上一行创建了一个 new 列表,并为其分配了num_list.您还可以对表单进行就地"分配

Notice that the line above creates a new list and assigns num_list to that. You can also do an "in-place" assignment of the form

num_list[:] = ...

不会在内存中创建新列表,而是修改num_list已经指向的内存位置.

which does not create a new list in memory, but instead modifies the memory location already being pointed to by num_list. This difference is explained in more detail here.