问题描述
首先我要告诉你这是给学校的,因为我正在学习用 Python 编码.请解释为什么我应该做某事:)!我希望学习而不仅仅是得到答案.
To start of I am telling you this is for school as I am learning to code with Python. Please do explain why I should do something :)! I am looking to learn not just getting the answer.
我试图摆脱列表中的负面项目.我想打印之前(包括负面项目)和之后(当然没有负面项目)的列表.我的问题是它打印出原始列表和新列表,在打印之前没有负面项目,在之后打印原始列表.像这样:
I am trying to get rid of the negative items in the list. I want to print the list Before (including the negative items) and after ( without the negative items of course).My problem is that it prints out the original list and the new list without negative items on the Before print and the original one on After.Like this:
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]
这就是我所做的,我似乎无法弄清楚我应该做什么......
This is what I've done and I just can't seem to figure out what I should do...
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
推荐答案
您没有修改函数中的全局变量 l
.
You aren't modifying global variable l
in your function.
我用 Python 提出了这段代码,它应该可以正常工作:
I propose this code in Python, which should work correctly:
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
时间更短.你怎么看?
这篇关于删除负值并打印原始列表和新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!