Python - 测试所有元素在矩阵的列中是否唯一
给定一个矩阵,测试是否所有列都包含唯一元素。
Input : test_list = [[3, 4, 5], [1, 2, 4], [4, 1, 10]]
Output : True
Explanation : 3, 1, 4; 4, 2, 1; 5, 4, 10; All elements are unique in columns.
Input : test_list = [[3, 4, 5], [3, 2, 4], [4, 1, 10]]
Output : False
Explanation : 3, 3, 4; 3 repeated twice.
方法 #1:使用循环 + set() + len()
在这种情况下,我们迭代每一列并使用 len() 使用 set size 测试唯一元素,如果发现任何列的大小不等于实际列表,则结果被标记掉。
Python3
# Python3 code to demonstrate working of
# Test if all elements Unique in Matrix Columns
# Using loop + set() + len()
# initializing list
test_list = [[3, 4, 5], [1, 2, 4], [4, 1, 10]]
# printing original lists
print("The original list is : " + str(test_list))
res = True
for idx in range(len(test_list[0])):
# getting column
col = [ele[idx] for ele in test_list]
# checking for all Unique elements
if len(list(set(col))) != len(col):
res = False
break
# printing result
print("Are all columns Unique : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test if all elements Unique in Matrix Columns
# Using loop + set() + len()
# initializing list
test_list = [[3, 4, 5], [1, 2, 4], [4, 1, 10]]
# printing original lists
print("The original list is : " + str(test_list))
res = True
for idx in range(len(test_list[0])):
# getting column
col = [ele[idx] for ele in test_list]
# checking for all Unique elements
if len(list(set(col))) != len(col):
res = False
break
# printing result
print("Are all columns Unique : " + str(res))
输出:
The original list is : [[3, 4, 5], [1, 2, 4], [4, 1, 10]]
Are all columns Unique : True
方法 #2:使用 all() + 列表推导式
这可以在单行中使用 all() 解决,它检查所有列,使用列表理解进行,如果所有列都返回 True,则 all() 返回 true。
蟒蛇3
# Python3 code to demonstrate working of
# Test if all elements Unique in Matrix Columns
# Using loop + set() + len()
# initializing list
test_list = [[3, 4, 5], [1, 2, 4], [4, 1, 10]]
# printing original lists
print("The original list is : " + str(test_list))
res = True
for idx in range(len(test_list[0])):
# getting column
col = [ele[idx] for ele in test_list]
# checking for all Unique elements
if len(list(set(col))) != len(col):
res = False
break
# printing result
print("Are all columns Unique : " + str(res))
输出:
The original list is : [[3, 4, 5], [1, 2, 4], [4, 1, 10]]
Are all columns Unique : True