[英]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.