简体   繁体   English

删除 python 中另一个列表中的项目的问题

[英]Issue with deleting Items in a list in another list in python

I have a code that essentially deletes any item in a list that is present in another list which contains more items that the list which deletes.我有一个代码,它基本上删除了另一个列表中存在的列表中的任何项目,该列表包含更多被删除的列表的项目。 The list which deletes contains image name of images i want to delete from the image upload input by user删除的列表包含我要从用户输入的图像上传中删除的图像的图像名称

This is the first code:这是第一个代码:

for i in images:
            if i.name in adi:
               # del images[images.index(i)]
               images.pop(images.index(i))

This works for small file inputs but whenever i try to upload up to 21 or 20 image inputs then it errors in the amount it deletes whilst not deleting some items to be deleted in the list.这适用于小文件输入,但每当我尝试上传最多 21 或 20 个图像输入时,它删除的数量就会出错,而不会删除列表中要删除的某些项目。 So i tried running the same code twice:所以我尝试两次运行相同的代码:

for i in images:
            if i.name in adi:
               # del images[images.index(i)]
               images.pop(images.index(i))
for k in images:
            if k.name in adi:
               images.pop(images.index(k))

Still with this, after accepting user input, there's still going to be at least one image remaining in the list that is meant to be deleted.尽管如此,在接受用户输入后,列表中仍将至少保留一张要删除的图像。 Is anything wrong with the logic i'm using for implementation and if something is, how should i implement it instead我用于实现的逻辑有什么问题吗?如果有问题,我应该如何实现它

Maybe this will work for you:也许这对你有用:

list_1 = [1, 2, 3, 4, 5]
list_2 = [2, 4]
list_2 = [x for x in list_1 if x not in list_2]
list_2

Output: Output:

[1, 3, 5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM