【问题标题】:seek for elements in a list in another one, if found delete it from first list, python在另一个列表中寻找元素,如果找到从第一个列表中删除它,python
【发布时间】:2021-07-14 01:41:14
【问题描述】:

我猜这是一个非常简单的问题,但我就是找不到如何让它发挥作用, 我有 2 个列表,一个是空的,另一个有 2 个元素,以便继续: 如果 list1 中的元素不在 list2 中,则将其从 list1 中删除,因为这种情况最后 list1 应该是空的,但事实证明它最后保持“橙色”!

#Try 1:
for element in list1:
   if element not in list2:
      list1.remove(element)

 print(list1)
 >['orange']


#Try 2:
list1 = ['apple','orange']
list2 = []
print("len",len(list1)-1)

for i in range(0,len(list1)-1):
    if list1[i] not in list2:
        list1.remove(list1[i])
        
print(list1)
>['orange']

提前致谢

【问题讨论】:

标签: python list compare


【解决方案1】:

尝试遍历 list1 的副本:

list1 = ['apple', 'orange']
list2 = []

for element in list1.copy():
   if element not in list2:
       list1.remove(element)


print(list1)

【讨论】:

    猜你喜欢
    • 2022-11-13
    • 2022-01-24
    • 2017-08-18
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多