如何删除列表中没有的第一个匹配项?

时间:2020-11-04 15:29:17

标签: python list

所以我有几个看起来像这样的列表: lst = [1、3、1、1]和lst2 = [3]

我需要首先删除“ 1”,但要删除一个特定的“ 1”:lst [2],然后将lst2中的“ 3”插入该特定位置。

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

非常感谢!

2 个答案:

答案 0 :(得分:0)

您可以使用del删除python中给定索引处的元素。要在特定位置插入元素,可以在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

答案 1 :(得分:0)

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,而不是从该循环中切掉的char discount_str[128]; snprintf(discount_str, sizeof(discount_str), "Discount %d", discount); printf("You paid € %.2f, %s", price, (price > 100 ? discount_str : "No Discount"));

我已经使用Python 3.8.1进行了尝试,请自己尝试并在注释中告诉我是否可行!

相关问题