📜  Python – 过滤具有所有相同元素的元组

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

Python – 过滤具有所有相同元素的元组

给定元组列表,过滤具有相同值的元组。

方法 #1:使用列表理解 + set() + len()

在此,我们检查集合转换元组的长度是否为 1,如果检查出,则将元组添加到结果中,否则省略。

Python3
# Python3 code to demonstrate working of
# Filter similar elements Tuples
# Using list comprehension + set() + len()
 
# initializing list
test_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# length is computed using len()
res = [sub for sub in test_list if len(set(sub)) == 1]
         
# printing results
print("Filtered Tuples : " + str(res))


Python3
# Python3 code to demonstrate working of
# Filter similar elements Tuples
# Using filter() + lambda + set() + len()
 
# initializing list
test_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# end result converted to list object
# filter extracts req. tuples
res = list(filter(lambda sub : len(set(sub)) == 1, test_list))
         
# printing results
print("Filtered Tuples : " + str(res))


输出
The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]
Filtered Tuples : [(6, 6, 6), (1, 1)]

方法 #2:使用 filter() + lambda + set() + len()

在此,我们使用 filter() 执行过滤任务,并使用 set() 和 len() 在 lambda函数中检查单个元素逻辑。

Python3

# Python3 code to demonstrate working of
# Filter similar elements Tuples
# Using filter() + lambda + set() + len()
 
# initializing list
test_list = [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# end result converted to list object
# filter extracts req. tuples
res = list(filter(lambda sub : len(set(sub)) == 1, test_list))
         
# printing results
print("Filtered Tuples : " + str(res))
输出
The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)]
Filtered Tuples : [(6, 6, 6), (1, 1)]