📜  Python - 删除重复元素的交叉列表同步

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

Python - 删除重复元素的交叉列表同步

给定两个列表,在删除第一个列表中的重复元素时,将列表的所有元素与其他列表同步。

方法 #1:使用循环 + dict()
上述功能提供了蛮力解决这个问题的方法。在此,我们使用字典和循环条件来记住元素及其对应项。

Python3
# Python3 code to demonstrate working of
# Cross List Sync on duplicate elements removal
# Using loop + dict()
 
# initializing lists
test_list1 = [2, 2, 3, 4, 4, 4, 5, 5, 6, 6]
test_list2 = [8, 3, 7, 5, 4, 1, 0, 9, 4, 2]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# Cross List Sync on duplicate elements removal
temp = dict()
a = []
for idx in range(len(test_list1)):
    if test_list1[idx] not in a:
        a.append(test_list1[idx])
         
        # performing memoize using dictionary
        temp[test_list1[idx]] = test_list2[idx]
 
res2 = list(temp.values())
res1 = a
 
# printing result
print("List 1 : " + str(res1))
print("Sync List : " + str(res2))


Python3
# Python3 code to demonstrate working of
# Cross List Sync on duplicate elements removal
# Using loop + zip()
 
# initializing lists
test_list1 = [2, 2, 3, 4, 4, 4, 5, 5, 6, 6]
test_list2 = [8, 3, 7, 5, 4, 1, 0, 9, 4, 2]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# Cross List Sync on duplicate elements removal
res1 = []
res2 = []
 
# both lists are combined index wise using zip()
for a, b in zip(test_list1, test_list2):
    if a not in res1:
        res1.append(a)
        res2.append(b)
         
# printing result
print("List 1 : " + str(res1))
print("Sync List : " + str(res2))


输出 :
The original list 1 : [2, 2, 3, 4, 4, 4, 5, 5, 6, 6]
The original list 2 : [8, 3, 7, 5, 4, 1, 0, 9, 4, 2]
List 1 : [2, 3, 4, 5, 6]
Sync List : [8, 7, 5, 0, 4]


方法 #2:使用循环 + zip()
这是可以执行此任务的另一种方式。在此,我们使用 zip() 同步两个列表。类似的记忆逻辑被实现为上述任务,并将相应的有效其他列表元素附加到结果中。

Python3

# Python3 code to demonstrate working of
# Cross List Sync on duplicate elements removal
# Using loop + zip()
 
# initializing lists
test_list1 = [2, 2, 3, 4, 4, 4, 5, 5, 6, 6]
test_list2 = [8, 3, 7, 5, 4, 1, 0, 9, 4, 2]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# Cross List Sync on duplicate elements removal
res1 = []
res2 = []
 
# both lists are combined index wise using zip()
for a, b in zip(test_list1, test_list2):
    if a not in res1:
        res1.append(a)
        res2.append(b)
         
# printing result
print("List 1 : " + str(res1))
print("Sync List : " + str(res2))
输出 :
The original list 1 : [2, 2, 3, 4, 4, 4, 5, 5, 6, 6]
The original list 2 : [8, 3, 7, 5, 4, 1, 0, 9, 4, 2]
List 1 : [2, 3, 4, 5, 6]
Sync List : [8, 7, 5, 0, 4]