📜  Python – 提取对称元组

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

Python – 提取对称元组

有时在使用Python元组时,我们可能会遇到需要提取所有对称对的问题,即对于任何 (x, y),我们都有 (y, x) 对存在。这类问题可以应用于日常编程和 Web 开发等领域。让我们讨论可以执行此任务的某些方式。

方法 #1:使用字典理解 + set()
上述功能的组合可以用来解决这个问题。在此,我们首先构造反向对,然后与原始列表对进行比较,并提取其中之一。 set() 用于删除重复项,以避免不必要的元素计算。

# Python3 code to demonstrate working of 
# Extract Symmetric Tuples
# Using dictionary comprehension + set()
  
# initializing list
test_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Extract Symmetric Tuples
# Using dictionary comprehension + set()
temp = set(test_list) & {(b, a) for a, b in test_list}
res = {(a, b) for a, b in temp if a < b}
  
# printing result 
print("The Symmetric tuples : " + str(res)) 
输出 :
The original list is : [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]
The Symmetric tuples : {(8, 9), (6, 7)}

方法 #2:使用Counter() + 列表推导
这是可以执行此任务的另一种方式。在这里,我们遵循类似的构造反向对的方法,但是在这里,我们计算相等的元素,计数为 2 的元素是重复的并且匹配反向元组。

# Python3 code to demonstrate working of 
# Extract Symmetric Tuples
# Using Counter() + list comprehension
from collections import Counter
  
# initializing list
test_list = [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Extract Symmetric Tuples
# Using Counter() + list comprehension<
temp = [(sub[1], sub[0]) if sub[0] < sub[1] else sub for sub in test_list]
cnts = Counter(temp)
res = [key for key, val in cnts.items() if val == 2]
  
# printing result 
print("The Symmetric tuples : " + str(res)) 
输出 :
The original list is : [(6, 7), (2, 3), (7, 6), (9, 8), (10, 2), (8, 9)]
The Symmetric tuples : [(7, 6), (9, 8)]