Python - 检查矩阵行中的相似元素
给定一个矩阵和列表,任务是编写一个Python程序来检查该行的所有矩阵元素是否与 List 的第 i个索引相似。
Input : test_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
Output : True
Explanation : All rows have same elements.
Input : test_list = [[1, 1, 4], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
Output : False
Explanation : All rows don’t have same elements.
方法#1:使用循环
在这里,我们遍历每一行并检查它在列表中的相似数字,如果一行中的所有元素都与列表中的第 i个元素相同,则返回 true,否则返回 false。
Python3
# Python3 code to demonstrate working of
# Similar all elements as List in Matrix rows
# Using loop
# initializing Matrix
test_list = [[1, 1, 1], [4, 4],
[3, 3, 3], [5, 5, 5, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing tar_list
tar_list = [1, 4, 3, 5]
res = True
flag = 0
for idx in range(len(test_list)):
for ele in test_list[idx]:
# checking for row index
# equal to list index elements
if ele != tar_list[idx]:
res = False
flag = 1
break
if flag:
break
# printing result
print("Are row index element similar\
to list index element ? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Similar all elements as List in Matrix rows
# Using all() + generator expression
# initializing Matrix
test_list = [[1, 1, 1], [4, 4],
[3, 3, 3], [5, 5, 5, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing tar_list
tar_list = [1, 4, 3, 5]
# nested all() used to check each element and rows
res = all(all(ele == tar_list[idx] for ele in test_list[idx])
for idx in range(len(test_list)) )
# printing result
print("Are row index element\
similar to list index element ? : " + str(res))
输出:
The original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
Are row index element similar to list index element ? : True
方法 #2:使用 all() +生成器表达式
在这里,我们使用 all() 检查所有元素是否相等,并再次使用 all() 检查所有元素是否遵循此模式。元素和行的迭代是使用生成器表达式完成的。
蟒蛇3
# Python3 code to demonstrate working of
# Similar all elements as List in Matrix rows
# Using all() + generator expression
# initializing Matrix
test_list = [[1, 1, 1], [4, 4],
[3, 3, 3], [5, 5, 5, 5]]
# printing original list
print("The original list is : " + str(test_list))
# initializing tar_list
tar_list = [1, 4, 3, 5]
# nested all() used to check each element and rows
res = all(all(ele == tar_list[idx] for ele in test_list[idx])
for idx in range(len(test_list)) )
# printing result
print("Are row index element\
similar to list index element ? : " + str(res))
输出:
The original list is : [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]]
Are row index element similar to list index element ? : True