📜  Python|记录联盟

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

Python|记录联盟

有时,在处理数据时,我们可能会遇到需要在收到的两个列表之间查找所有记录的问题。这是一个非常常见的问题,记录通常以元组的形式出现。让我们讨论一些可以解决这个问题的方法。

方法#1:使用列表推导
可以选择列表理解作为在一行中执行此任务的方法,而不是运行循环来查找联合元素。在此,我们只迭代单个列表并检查是否有任何元素出现在另一个列表中。如果不是,我们再次填充制作列表。

# Python3 code to demonstrate working of
# Records Union
# Using list comprehension
  
# Initializing lists
test_list1 = [('gfg', 1), ('is', 2), ('best', 3)]
test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Records Union
# Using list comprehension
res1 = [ele1 for ele1 in test_list1]
res2 = [ele2 for ele2 in test_list2 if ele2 not in res1]
res = res1 + res2
  
# printing result
print("The union of data records is : " + str(res))
输出 :
The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
The original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]
The union of data records is : [('gfg', 1), ('is', 2), ('best', 3), ('i', 3), ('love', 4)]

方法 #2:使用set.union()
也可以使用通用集合并集以较小的方式执行此任务。在此,我们首先将记录列表转换为一个集合,然后使用 union() 执行它的联合。

# Python3 code to demonstrate working of
# Records Union
# Using set.union()
  
# Initializing lists
test_list1 = [('gfg', 1), ('is', 2), ('best', 3)]
test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# Records Union
# set.union()
res = list(set(test_list1).union(set(test_list2)))
  
# printing result
print("The union of data records is : " + str(res))
输出 :
The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
The original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]
The union of data records is : [('gfg', 1), ('is', 2), ('best', 3), ('i', 3), ('love', 4)]