📜  从其他列表中删除重复元素索引的Python程序

📅  最后修改于: 2022-05-13 01:55:00.812000             🧑  作者: Mango

从其他列表中删除重复元素索引的Python程序

给定两个列表,任务是编写一个Python程序,从第二个列表中删除所有索引元素,这些元素是第一个列表中的重复元素索引。

例子:

方法一:使用列表推导+循环+ enumerate()

在这里,我们执行使用 enumerate() 获取所有索引的任务,并使用 set 循环来存储已经出现的元素。然后,省略来自其他列表的相同索引。

Python3
# Python3 code to demonstrate working of
# Remove duplicate elements index from other list
# Using list comprehension + loop + enumerate()
  
# initializing lists
test_list1 = [3, 5, 6, 5, 3, 7, 8, 6]
test_list2 = [1, 7, 6, 3, 7, 9, 10, 11]
               
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
oc_set = set() 
temp = [] 
  
# getting duplicate elements list
for idx, val in enumerate(test_list1): 
    if val not in oc_set: 
        oc_set.add(val)          
    else: 
        temp.append(idx)
  
# excluding duplicate indices from other list
res = [ele for idx, ele in enumerate(test_list2) if idx not in temp]
  
# printing result
print("The list after removing duplicate indices : " + str(res))


Python3
# Python3 code to demonstrate working of
# Remove duplicate elements index from other list
# Using list comprehension + enumerate()
  
# initializing lists
test_list1 = [3, 5, 6, 5, 3, 7, 8, 6]
test_list2 = [1, 7, 6, 3, 7, 9, 10, 11]
               
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# getting duplicate elements list using list comprehension
temp = [idx for idx, val in enumerate(test_list1) if val in test_list1[:idx]]
  
# excluding duplicate indices from other list
res = [ele for idx, ele in enumerate(test_list2) if idx not in temp]
  
# printing result
print("The list after removing duplicate indices : " + str(res))


输出:

The original list 1 is : [3, 5, 6, 5, 3, 7, 8, 6]
The original list 2 is : [1, 7, 6, 3, 7, 9, 10, 11]
The list after removing duplicate indices : [1, 7, 6, 9, 10]

方法二:使用列表推导+ enumerate()

在这种情况下,我们以速记方式执行与上述类似的任务,使用 enumerate() 和列表推导来提取索引。

蟒蛇3

# Python3 code to demonstrate working of
# Remove duplicate elements index from other list
# Using list comprehension + enumerate()
  
# initializing lists
test_list1 = [3, 5, 6, 5, 3, 7, 8, 6]
test_list2 = [1, 7, 6, 3, 7, 9, 10, 11]
               
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# getting duplicate elements list using list comprehension
temp = [idx for idx, val in enumerate(test_list1) if val in test_list1[:idx]]
  
# excluding duplicate indices from other list
res = [ele for idx, ele in enumerate(test_list2) if idx not in temp]
  
# printing result
print("The list after removing duplicate indices : " + str(res))

输出:

The original list 1 is : [3, 5, 6, 5, 3, 7, 8, 6]
The original list 2 is : [1, 7, 6, 3, 7, 9, 10, 11]
The list after removing duplicate indices : [1, 7, 6, 9, 10]