我開始告訴你這是爲了學校,因爲我正在學習使用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
由於您沒有限制使用額外的列表,爲什麼不通過列表並只添加元素到新列表,如果他們是積極的? 'newList = [ele for ele在listOfIntegers如果ele> = 0]' –
您不修改函數內部的全局'l'。你正在創建一個局部變量'l'並在那個變量上工作。和你的'打印'之後:「,l'然後再次打印出全局變量,它沒有被修改 – UnholySheep