[英]removing a number from a list
我被困在一個循環問題的一部分上。 我必須從 list1 中刪除“number”的所有實例。 所以讓我們說 list1 是 (1,2,3) 和 num 是 2。我必須返回的列表是 (1,3)
def remove(list1,num)
list1=list1
num = num
這就是所給的。 到目前為止,我有這個:
def remove(list1,num)
list1=list1
num=num
if num in list1:
這就是我被卡住的地方,因為我不知道如何在編碼中說“從列表中刪除 num”,我也不允許使用 .remove。
將不勝感激的幫助。
聽起來這是一個家庭作業問題,尤其是因為您不能使用.remove
。
鑒於此,您的老師可能希望您采用如下所示的手動方法:
.append
到您的新列表中(如果你不想自己寫代碼,鼠標懸停)
\n def 刪除(list1, num):\n 新列表 = []\n 對於列表 1 中的項目:\n 如果項目 != num:\n new_list.append(item)\n 返回新列表
使用列表理解:
list1 = [1,2,3]
num = 2
new_list = [i for i in list1 if i != num]
print(new_list)
>> [1,3]
def remove(item,given_list):
new_list = []
for each in given_list:
if item != each:
new_list.append(each)
return new_list
print(remove(2,[1,2,3,1,2,1,2,2,4]))
#outputs [1, 3, 1, 1, 4]
雖然我的回答和其他人一樣強烈,但我覺得這是思考如何從列表中刪除項目的基本方式。 它使人們能夠從基本層面了解正在發生的事情。
基本上我們采用 2 個輸入,要刪除的項目和要從中刪除的列表。 它循環遍歷input_list
並檢查該item
是否與我們要刪除的item
相同,如果不相同,我們append
其append
到新列表中,並返回新列表。
我們不想在循環時刪除列表中的項目,因為它可能會導致不受歡迎的循環。 例如,如果我們有example_list=[1,2,3]
並且我們在for loop
的第二次迭代中並且我們刪除了 2 ,它將嘗試去我們不希望它去的地方。
考慮在內:
list=[1,2,3,2]
您可以使用以下命令檢查元素是否在列表中:
if num in list
然后刪除:
list.remove(num)
並遍歷它
例子:
>>> list=[1,2,3]
>>> list.remove(2)
>>> print list
[1, 3]
要使用純循環並使用列表索引刪除:
#!/usr/bin/env python
from __future__ import print_function
def remove(item, old_list):
while True:
try:
# find the index of the item
index = old_list.index(item)
# remove the item found
del old_list[index]
except ValueError as e:
# no more items, return
return old_list
a_list = [1, 2, 3, 2, 1, 3, 2, 4, 2]
print(remove(2, a_list))
如果可能的話,當然,您應該使用列表推導式,這是 Pythonic 並且更容易!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.