Python:从数字列表中删除负数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20959964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Removing negatives from a list of numbers
提问by user3161743
The question is to remove negatives from 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)
当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(): numbers = input("请输入数字列表:") 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()
回答by John1024
Much simpler:
更简单:
>>> a = [ 1, 2, 3, -3, 6, -1, -3, 1]
>>> [x for x in a if x >= 0 ]
[1, 2, 3, 6, 1]
If you really do want to loop, try this:
如果你真的想循环,试试这个:
def remove_negs(num_list):
r = num_list[:]
for item in num_list:
if item < 0:
r.remove(item)
print r
This does what you want:
这做你想要的:
>>> remove_negs([ 1, 2, 3, -3, 6, -1, -3, 1])
[1, 2, 3, 6, 1]
The key is that the assignment statement r = num_list[:]makes a copy of num_list. In order not to confuse the loop, We then remove items from rrather than from the list we are looping over.
关键是赋值语句r = num_list[:]复制了num_list。为了不混淆循环,我们然后从而r不是从我们正在循环的列表中删除项目。
More:Python's treatment of variables is a bit subtle. Python keeps variable names, like ror num_listseparate from variable data, such as [1, 2, 3, 6, 1]. The names are merely pointers to the data. Consider the assignment statement:
更多:Python 对变量的处理有点微妙。Python 保留变量名称,如变量数据r或num_list与变量数据分开,例如[1, 2, 3, 6, 1]. 名称只是指向数据的指针。考虑赋值语句:
r = num_list
After this statement is run, rand num_listboth point to the same data. If you make a change to r's data, you are also making a change to num_list's data because they both point to the samedata. Now, consider:
该语句后运行,r并且num_list都指向相同的数据。如果您对r的数据进行了更改,那么您也在对num_list的数据进行了更改,因为它们都指向相同的数据。现在,考虑:
r = num_list[:]
This statement tells python to modify num_list's data by taking only certain elements of it. Because of this, python makes a copy of num_list's data. It just so happens that [:]specifies that we want all of num_list's data unchanged but that doesn't stop python from making a copy. The copy is assigned to r. This means that rand mum_listnow point to differentdata. We can make changes to r's data and it doesn't affect num_list's data because they have differentdata.
该语句告诉 pythonnum_list通过仅获取数据的某些元素来修改数据。因此,python 会复制num_list的数据。碰巧[:]指定我们希望所有num_list的数据不变,但这并不能阻止python制作副本。副本分配给r. 这意味着,r和mum_list现在都指向不同的数据。我们可以对r的数据进行更改,并且不会影响num_list的数据,因为它们具有不同的数据。
If this is new to you, you might want to look at this tutorial about python's approach to variable names and variable data: Understanding Python variables and Memory Management
如果这对你来说是新的,你可能想看看这个关于 python 变量名和变量数据方法的教程: 了解 Python 变量和内存管理
Examples:
例子:
>>> a = [ 1, 2, 3, -3, 6, -1, -3, 1]
>>> b = a # a and b now point to the same place
>>> b.remove(-1)
>>> a
[1, 2, 3, -3, 6, -3, 1]
Contrast with:
对比:
>>> a = [ 1, 2, 3, -3, 6, -1, -3, 1]
>>> b = a[:] # a and b now point to different data
>>> b
[1, 2, 3, -3, 6, -1, -3, 1]
>>> b.remove(-1)
>>> b
[1, 2, 3, -3, 6, -3, 1]
>>> a
[1, 2, 3, -3, 6, -1, -3, 1]
回答by arshajii
It's generally a bad idea to remove elements from a list while iterating over it (see the linkin 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]
Notice that the line above creates a newlist and assigns num_listto 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.
它不会在内存中创建一个新列表,而是修改已经被指向的内存位置num_list。此处更详细地解释了这种差异。
回答by abarnert
From a comment on arshajii's answer:
来自对 arshajii 回答的评论:
but that's removing the negative numbers. i need the negative signs removed but still keep the number in the list.
但这是删除负数。我需要删除负号,但仍将数字保留在列表中。
Removing the negative numbers is exactly what your code is clearly trying to do, and it's also the only way to get the desired result:
删除负数正是您的代码显然想要做的事情,这也是获得所需结果的唯一方法:
THe result is suppose to be [1, 2, 3, 6, 3, 1]
结果假设为 [1, 2, 3, 6, 3, 1]
But if you really want to "remove the negative signs" from the numbers, that's even easier. For example, to remove the negative sign from -3, you just negate it and get 3, right? You can do this in-place, as in your existing code:
但如果你真的想从数字中“去除负号”,那就更容易了。例如,要从 中删除负号-3,您只需将其取反并得到3,对吗?您可以就地执行此操作,就像在现有代码中一样:
for index, item in enumerate(num_list):
if item < 0:
num_list[index] = -item
… or in a list comprehension, as in arshajii's:
... 或者在列表理解中,如 arshajii 的:
num_list = [-item if item < 0 else item for item in num_list]
And it's even easier with the absfunction, which does exactly that—negates negative numbers, leaves positive and zero alone:
使用该abs函数甚至更容易,它正是这样做的 - 否定负数,单独留下正数和零:
num_list = [abs(item) for item in num_list]
Either way, of course, this will give you [1, 2, 3, 3, 6, 1, 3, 1], which is the wrong answer… but if your comment is correct, it's the answer you asked for.
无论哪种方式,当然,这都会给你[1, 2, 3, 3, 6, 1, 3, 1],这是错误的答案……但如果你的评论是正确的,这就是你要求的答案。
回答by alvas
Other the the conventional variable operator non-variableTry some yoda conditionstoo =)
其他常规也variable operator non-variable尝试一些尤达条件=)
>>> [i for i in x if 0 <= i]
[1, 2, 3, 6, 1]
回答by Hiskel Kelemework
to strip the numbers off their negative signs, this is the easiest thing to do
去掉负号上的数字,这是最简单的事情
def remove_negs(somelist):
for each in somelist:
if each < 0:
somelist[somelist.index(each)] = -each
print(somelist)
for example
例如
rNegatives([-2,5,11,-1])
rNegatives([-2,5,11,-1])
prints out
打印出来
[2,5,11,1]
[2,5,11,1]
回答by sergiohzlz
Another solution
另一种解决方案
filter( lambda x: x>0, [ 1, 2, 3, -3, 6, -1, -3, 1])
[1, 2, 3, 6, 1]
回答by Amjad
I think an elegant solution can be like this:
我认为一个优雅的解决方案可以是这样的:
import numpy as np
x = [1, 2, 3, -3, 6, -1, -3, 1] # raw data
x = np.array(x) # convert the python list to a numpy array, to enable
matrix operations
x = x[x >=0] # this section `[x >=0]` produces vector of True and False
values, of the same length as the list x
# as such, this statement `x[x >=0]` produces only the
positive values and the zeros
print(x)
[1 2 3 6 1] # the result

