【问题标题】:How can I remove not a first occurrence in the list?我如何才能删除列表中的第一次出现?
【发布时间】:2020-11-04 15:29:17
【问题描述】:

所以我有几个列表如下所示: lst = [1, 3, 1, 1] 和 lst2 = [3]

我需要从 lst 中删除“1”,但要删除特定的“1”:lst[2],并且我需要将 lst2 中的“3”插入到该特定位置。

删除并没有真正的帮助,因为它删除了第一个匹配项。

非常感谢!

【问题讨论】:

  • 欢迎来到 Stackoverflow,请阅读How To Ask。请特别注意明确您的问题并发送至How To Create MCVE。确保使用适当的标签(编程语言、相关技术等)标记您的问题。您在发布一个好问题上付出的努力越多:一个易于阅读、理解并且是 on topic 的问题 - 它吸引相关人员的机会就越高,您将更快地获得帮助。祝你好运!
  • 您能描述一下您的问题的一般形式吗?你对那个具体的例子没有多大帮助

标签: python list


【解决方案1】:

您可以使用 del 删除 python 中给定索引处的元素。要在特定位置插入元素,可以使用 in insert(index, element)。在您的情况下,以下将起作用:

lst = [1, 3, 1, 1]
lst2 = [3]
del lst[2] #This will delete element at position 2 from lst list
lst.insert(2,3) #This will insert element 3 at position 2 in lst

【讨论】:

    【解决方案2】:
    lst=[int(input("Enter a number into the list: "))]
    lstcopy=lst
    while True:
        new=input("Enter one more number into the list: ")
        if not new:
            break
        lst.append(int(new))
    findMe=int(input("Enter the number to find: "))
    findMeOccurence=int(input("Enter the occurence number of "+str(findMe)+" that you want to find: "))
    idx=-1
    error=False
    try:
        for i in range(findMeOccurence):
            idx+=1
            lstcopy=lstcopy[idx:]
            idx=lstcopy.index(findMe)
    except:
        print("Your number does not exist at that occurence.")
        error=True
    if not error:
        del lst[idx+1]
        print("\nThis is your list with "+str(findMe)+" removed at occurence "+str(findMeOccurence)+":\n"+str(lst))
    

    它的作用是获取您的列表(您可以对其进行预设并删除列表获取代码),将其复制到lstcopy,获取要查找的号码(再次您可以预设)以及要查找的位置它(在这里也可以进行预设)。然后将idx 设置为-1 并将error 设置为False。在try 内部,完成了一个循环:

    1. idx 增加 1
    2. 剪切 lstcopy 以便下一步不会递归地执行此操作
    3. 使用index 获取新的idx

    index 在找不到给定项目时引发异常,这将被except 捕获,表示您的号码不存在(因为循环尚未完成,所以发生的是未找到)。然后将error 设置为True

    在结尾部分,它检查 error 是否为 False(因为默认情况下它是 False 并且我们使用的是 not 关键字),如果是这样,这意味着错误消息 ("那个时候你的号码不存在。”)没有给出,所以使用del lst[idx+1]删除索引并向用户显示新列表。这就是创建lstcopy 的原因:因为最后,它需要完整的lstdel,而不是从那个循环中分割的lstcopy

    我在 Python 3.8.1 上试过这个,你自己试试,如果成功的话在 cmets 中告诉我!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多