删除负值并打印原始列表和新列表

时间:2016-10-16 18:06:39

标签: python python-2.7

首先,我告诉你这是为了学校,因为我正在学习用Python编写代码。请解释我为什么要做某事:)!我希望学习的不仅仅是得到答案。

我试图摆脱列表中的负面项目。我想打印列表之前(包括负面项目)和之后(当然没有负面项目)。 我的问题是,它打印出原始列表和新列表,而不在“打印”前面显示负面项目,在“打印”上打印原始列表。 像这样:

Before: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14,
-2, -9, -14, 2, -10, -5, 8, 7]
[2, 7, 13, 13, 5, 11, 10, 5, 0, 2, 8, 7]
After: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14, -2, -9,
-14, 2, -10, -5, 8, 7] 

这就是我所做的,我似乎无法弄清楚我该做什么......

import random

def removeNegatives(listOfIntegers):
    l = listOfIntegers[:]           #takes a copy of the list
    for item in listOfIntegers:     
        if item < 0:                #checks if it is lower than 0
           l.remove(item)
    print l



l = []
for i in xrange(0, random.randint(15,25)): #gives me the random numbers
  l.append(random.randint(-15,15))

print "Before:", l #should only print out the original list of numbers
removeNegatives(l)
print "After:", l #should only print out the new list without the numbers that are <0

4 个答案:

答案 0 :(得分:1)

您不是在修改函数中的全局变量l

我在Python中提出这个代码,它应该可以正常工作:

import random

def removeNegatives(listOfIntegers):
    return [x for x in listOfIntegers if not x < 0]

l = []
for i in xrange(0, random.randint(15,25)): #gives me the random numbers
    l.append(random.randint(-15,15))

print "Before:", l #should only print out the original list of numbers
l = removeNegatives(l)
print "After:", l #should only print out the new list without the numbers that are <0

它缩短了。你觉得怎么样?

答案 1 :(得分:1)

&#34;最干净&#34;修改外部列表的方法是更改​​其内容而不重新分配 - 这会更改列表对象引用。循环遍历列表时不能删除元素,并且在迭代复制时删除每个不兼容的元素是非常无效的。

但您可以重新分配列表内容而无需重新分配列表对象引用 - 使用作业左侧的切片

def removeNegatives(listOfIntegers):
    listOfIntegers[:] = filter(lambda x: x >= 0, listOfIntegers)

此代码创建新的非负值列表,并替换外部范围列表的整个内容。

答案 2 :(得分:0)

刚看到你的评论相对于无法修改l = []

下面的代码

在这种情况下,您需要重新分配来自函数的listOfIntegers

def removeNegatives(listOfIntegers):
    global l
    k = listOfIntegers[:]           #takes a copy of the list
    for item in listOfIntegers:     
        if item < 0:                #checks if it is lower than 0
           k.remove(item)
    print k
    l = k

当你进入函数时,你制作了全局的副本,你只需要在离开时将它重新指向修改过的副本。

编辑:有关在迭代时修改列表的其他注释不准确,因为您没有修改正在迭代的列表,您正在修改&#34;复制&#34;的清单。虽然其他人提出了改善方法简洁性的好建议,但您的原始方法完全适用于上述调整。

Edit2:volcano&#39;评论&#39;相对于全局是正确的,应该在def中添加全局语句以这种方式执行它。参考火山的最佳方法的答案,但我将讨论点留下来。

答案 3 :(得分:0)

由于您正在学习Python,因此这是一个学习list comprehension的好地方:

$ cat /tmp/tmp.py
_list = [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14,
        -2, -9, -14, 2, -10, -5, 8, 7]

print("Before:",_list)
print("After:",[a for a in _list if a >= 0])

$ python3 /tmp/tmp.py
Before: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14, -2, -9, -14, 2, -10, -5, 8, 7]
After: [2, 7, 13, 13, 5, 11, 10, 5, 0, 2, 8, 7]

正如您所看到的,在列表理解阶段消除负数是简洁明了的,如果您测试它,您发现它比使用循环的可比解决方案更快。 / p>