【问题标题】:How to remove elements from two lists from the same index?如何从同一索引的两个列表中删除元素?
【发布时间】:2023-02-23 04:09:00
【问题描述】:
list1 = [0,10,20,0,40,50] 
list2 = [1,2,3,4,5,6] 
list3 = []

我想删除 list1 中的所有零和 list2 中的相应元素。我可以从 list1 中删除零,但无法从 list2 中删除相应的元素。

for i in list1[:]:
    if i != 0:
    list3.append(i)
                               
for i in range(len(list3)):
    list2.append(i)
                
for i in list3[:]:
    list2.remove(i)


Desired result:
    list1 = [10,20,40,50]
    list2 = [2,3,5,6]

【问题讨论】:

    标签: python-3.x list for-loop


    【解决方案1】:

    这是一种方法,您没有提供有关该列表 3 的任何信息。试试下面的代码:

    list1 = [0, 10, 20, 0, 40, 50]
    list2 = [1, 2, 3, 4, 5, 6]
    
    # Indexes of the elements to remove
    indexes_to_remove = [i for i, x in enumerate(list1) if x == 0]
    
    # Remove the elements from list1 and list2 in reverse order to avoid issues
    for i in reversed(indexes_to_remove):
        del list1[i]
        del list2[i]
    
    # Return lists
    print(list1)
    print(list2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-01
      • 2010-10-12
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多