Python|删除元组矩阵中的相似元素行
有时,在处理数据时,我们可能会遇到一个问题,即我们需要在元组矩阵行中的所有元素都相同的情况下从元组矩阵中删除元素。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + all()
可以使用上述功能的组合来执行此任务。在此,我们使用列表推导遍历所有行,并在all()
的帮助下删除与行列中初始元素匹配的所有元素。
# Python3 code to demonstrate working of
# Remove similar element rows in tuple Matrix
# using list comprehension + all()
# initialize tuple
test_tup = ((1, 3, 5), (2, 2, 2),
(9, 10, 10), (4, 4, 4))
# printing original tuple
print("The original tuple : " + str(test_tup))
# Remove similar element rows in tuple Matrix
# using list comprehension + all()
res = tuple(ele for ele in test_tup if not all(sub == ele[0] for sub in ele))
# printing result
print("The tuple after removal of like-element rows : " + str(res))
输出 :
The original tuple : ((1, 3, 5), (2, 2, 2), (9, 10, 10), (4, 4, 4))
The tuple after removal of like-element rows : ((1, 3, 5), (9, 10, 10))
方法 #2:使用set()
+ 生成器表达式
此任务也可以使用给定的功能来执行。在此,我们只使用 set() 检查减少行的长度是否大于 1。如果是,我们知道它是要删除的目标行。
# Python3 code to demonstrate working of
# Remove similar element rows in tuple Matrix
# using set() + generator expression
# initialize tuple
test_tup = ((1, 3, 5), (2, 2, 2),
(9, 10, 10), (4, 4, 4))
# printing original tuple
print("The original tuple : " + str(test_tup))
# Remove similar element rows in tuple Matrix
# using set() + generator expression
res = tuple(ele for ele in test_tup if len(set(ele)) > 1)
# printing result
print("The tuple after removal of like-element rows : " + str(res))
输出 :
The original tuple : ((1, 3, 5), (2, 2, 2), (9, 10, 10), (4, 4, 4))
The tuple after removal of like-element rows : ((1, 3, 5), (9, 10, 10))