📜  Python – 过滤唯一值元组

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

Python – 过滤唯一值元组

给定一个元组列表,过滤不包含重复项的元组。

方法 #1:使用循环 + set()

在这种情况下,所有的元组都被迭代,并且重复测试是使用 set() 完成的,如果集合的长度与元组相同,则它不包含重复。

Python3
# Python3 code to demonstrate working of 
# Filter unique valued tuples
# Using loop + set()
  
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = []
  
for sub in test_list:
      
    # checking lengths to be equal
    if len(set(sub)) == len(sub):
        res.append(sub)
          
# printing results
print("Filtered tuples : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Filter unique valued tuples
# Using list comprehension
  
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# list comprehension used to filter
res = [sub for sub in test_list if len(set(sub)) == len(sub)]
          
# printing results
print("Filtered tuples : " + str(res))


输出
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
Filtered tuples : [(3, 5, 6, 7), (9, 4)]

方法#2:使用列表推导

这执行与上述类似的任务,不同之处在于这是一个衬垫和紧凑型。

Python3

# Python3 code to demonstrate working of 
# Filter unique valued tuples
# Using list comprehension
  
# initializing list
test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# list comprehension used to filter
res = [sub for sub in test_list if len(set(sub)) == len(sub)]
          
# printing results
print("Filtered tuples : " + str(res))
输出
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)]
Filtered tuples : [(3, 5, 6, 7), (9, 4)]