【问题标题】:Python -Cannot remove list itemPython - 无法删除列表项
【发布时间】:2020-02-06 17:29:47
【问题描述】:

我必须删除特定的给定元素。我用list1=[0,1,2,2,3,0,4,2]remove_element=2

def fun(list1,remove_element):
   if len(list1)==0:
       return 0
   for i in range(len(list1)):
       if remove_element==list1[i]:
           list1.remove(remove_element)
   return list1

这是我得到的错误:

Traceback (most recent call last):
  File "<pyshell#205>", line 1, in <module>
   print(fun(list1,remove_element))
   File "<pyshell#204>", line 5, in fun
        if remove_element==list1[i]:
    IndexError: list index out of range

【问题讨论】:

  • return [x for x in list1 if x != remove_element]
  • 你的问题是,一旦你从列表中删除元素,它就会变短一个元素,所以一旦你删除了项目,你迭代的范围就会比列表长

标签: python list indexing range


【解决方案1】:

另一个更短的解决方案是

def fun(list1,remove_element):
    while remove_element in list1:
        list1.remove(remove_element)
    return list1

【讨论】:

  • 嗨,感谢您的好评。但如果你能指出我的代码中的错误并纠正它,那对我来说将是很好的学习。谢谢
  • 您的代码的问题是您的循环依赖于预先计算的 len(list),但是您正在删除列表中的元素,因此循环时实际的 len 是不同的。此外,remove 方法会自动删除第一个匹配的元素,因此您无需遍历列表。
  • 这当然可行,但可能值得注意的是复杂性是二次方的(因为 in 在列表中,而不是集合中),因此非常未优化。返回一个新列表会更快,但也会占用更多空间。生成器功能可能会更好
【解决方案2】:

试试这个

def fun(list1,remove_element):
    if len(list1)==0:
        return 0
    newlist = list(filter((remove_element).__ne__, list1))
    print(newlist)
    return newlist

跑步

fun(['1', '2', '3'], '1')

get [2,3]

【讨论】:

  • hii,感谢您的回复,但它不适用于 list1=[0,1,2,2,3,0,4,2],remove_element=2。它给出输出 [0, 1, 3, 0, 4, 2],但我期待 output=[0, 1, 3, 0, 4]
  • @viveksingh 试试newlist = list(filter((remove_element).__ne__, list1))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多