问题是要去掉数字中的负数。
当执行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()发布于 2014-01-07 05:56:21
在遍历列表时从列表中删除元素通常不是一个好主意(请参阅我的注释中的the link来解释为什么会这样)。一种更好的方法是使用list comprehension
num_list = [item for item in num_list if item >= 0]请注意,上面的代码行创建了一个新列表,并将num_list分配给该列表。您还可以对表单进行“就地”分配
num_list[:] = ...它不会在内存中创建新的列表,而是修改num_list已经指向的内存位置。这种差异在here中有更详细的解释。
发布于 2014-01-07 05:56:04
简单得多:
>>> a = [ 1, 2, 3, -3, 6, -1, -3, 1]
>>> [x for x in a if x >= 0 ]
[1, 2, 3, 6, 1]如果你真的想要循环,试试这个:
def remove_negs(num_list):
r = num_list[:]
for item in num_list:
if item < 0:
r.remove(item)
print r这就是你想要的:
>>> remove_negs([ 1, 2, 3, -3, 6, -1, -3, 1])
[1, 2, 3, 6, 1]关键是赋值语句r = num_list[:]复制了num_list。为了不混淆循环,然后我们从r中删除项,而不是从我们要循环的列表中删除项。
更多:Python对变量的处理有点微妙。Python将变量名(如r或num_list )与变量数据(如[1, 2, 3, 6, 1] )分开。名称仅仅是指向数据的指针。考虑赋值语句:
r = num_list运行此语句后,r和num_list都指向相同的数据。如果您更改了r的数据,那么您也将更改num_list的数据,因为它们都指向相同的数据。
r = num_list[:]这条语句告诉python修改num_list的数据,只取其中的某些元素。正因为如此,python复制了num_list的数据。碰巧[:]指定我们希望num_list的所有数据保持不变,但这并没有阻止python复制。副本被分配给r。这意味着r和mum_list现在指向不同的数据。我们可以更改r的数据,但这不会影响num_list的数据,因为它们具有不同的数据。
如果这对您来说是新的,那么您可能想看看本教程,了解python处理变量名和变量数据的方法:Understanding Python variables and Memory Management
示例:
>>> 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]对比:
>>> 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]发布于 2017-09-29 08:52:13
另一种解决方案
filter( lambda x: x>0, [ 1, 2, 3, -3, 6, -1, -3, 1])
[1, 2, 3, 6, 1]https://stackoverflow.com/questions/20959964
复制相似问题