Python - 列表保持重复的区别
发现列表之间的差异的问题,即删除出现在一个列表中而不出现在另一个列表中的元素之前已讨论过。但是集合的使用忽略了重复,我们有时需要删除列表中出现的确切元素。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的粗暴方式。在这种情况下,我们以每次删除元素并打破循环以一次删除一个元素的形式提取元素。
# Python3 code to demonstrate
# Difference of List keeping duplicates
# using loop
# Initializing lists
test_list1 = [4, 5, 7, 4, 3]
test_list2 = [7, 3, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Difference of List keeping duplicates
# using loop
for ele in test_list2:
for sub in test_list1:
if ele == sub:
test_list1.remove(sub)
break
# printing result
print ("List after performing difference : " + str(test_list1))
输出 :
The original list 1 is : [4, 5, 7, 4, 3]
The original list 2 is : [7, 3, 4]
List after performing difference : [5, 4]
方法 #2:使用pop() + list comprehension + index()
也可以使用上述功能的组合来执行此任务。在此,我们只使用列表推导迭代列表并使用 index() 和 pop() 删除元素。
# Python3 code to demonstrate
# Difference of List keeping duplicates
# using pop() + list comprehension + index()
# Initializing lists
test_list1 = [4, 5, 7, 4, 3]
test_list2 = [7, 3, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Difference of List keeping duplicates
# using pop() + list comprehension + index()
[test_list1.pop(test_list1.index(idx)) for idx in test_list2]
# printing result
print ("List after performing difference : " + str(test_list1))
输出 :
The original list 1 is : [4, 5, 7, 4, 3]
The original list 2 is : [7, 3, 4]
List after performing difference : [5, 4]