Python程序删除矩阵中具有重复元素的行
给定 Matrix,删除其中包含重复元素的所有行。
Input : test_list = [[4, 3, 2], [7, 6, 7], [2, 4, 4], [8, 9, 9]]
Output : [[4, 3, 2]]
Explanation : [4, 3, 2] is the only unique row.
Input : test_list = [[4, 3, 3, 2], [7, 6, 7], [2, 4, 4], [8, 9, 9]]
Output : []
Explanation : No unique row.
方法 1:使用列表推导 + set() + len()
在这种情况下,我们只提取在将其转换为集合后保持相同长度的行。
Python3
# initializing list
test_list = [[4, 3, 2], [7, 6, 7], [2, 4, 5], [8, 9, 9]]
# printing original list
print("The original list is : " + str(test_list))
# set() removing all elements
# list comprehension used to filter
res = [sub for sub in test_list if len(set(sub)) == len(sub)]
# printing result
print("Rows after removal : " + str(res))
Python3
# initializing list
test_list = [[4, 3, 2], [7, 6, 7], [2, 4, 5], [8, 9, 9]]
# printing original list
print("The original list is : " + str(test_list))
# set() removing all elements
# filter() used to filter
res = list(filter(lambda ele: len(set(ele)) == len(ele), test_list))
# printing result
print("Rows after removal : " + str(res))
输出
The original list is : [[4, 3, 2], [7, 6, 7], [2, 4, 5], [8, 9, 9]]
Rows after removal : [[4, 3, 2], [2, 4, 5]]
方法 #2:使用 filter() + lambda + set() + len()
在此,我们使用 filter() + lambda 函数执行过滤任务,并使用 set 和 len() 进行检查。
蟒蛇3
# initializing list
test_list = [[4, 3, 2], [7, 6, 7], [2, 4, 5], [8, 9, 9]]
# printing original list
print("The original list is : " + str(test_list))
# set() removing all elements
# filter() used to filter
res = list(filter(lambda ele: len(set(ele)) == len(ele), test_list))
# printing result
print("Rows after removal : " + str(res))
输出
The original list is : [[4, 3, 2], [7, 6, 7], [2, 4, 5], [8, 9, 9]]
Rows after removal : [[4, 3, 2], [2, 4, 5]]