Python – 测试所有行是否与其他矩阵有任何共同元素


当需要测试所有行是否与其他矩阵有任何共同元素时,可以使用简单的迭代和标志值。

示例

以下是相同的演示

Open Compiler
my_list_1 = [[3, 16, 1], [2, 4], [4, 31, 31]] my_list_2 = [[42, 16, 12], [42, 8, 12], [31, 7, 10]] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) my_result = True for idx in range(0, len(my_list_1)): temp = False for element in my_list_1[idx]: if element in my_list_2[idx]: temp = True break if not temp : my_result = False break if(temp == True): print("The two matrices contain common elements") else: print("The two matrices don't contain common elements")

输出

The first list is :
[[3, 16, 1], [2, 4], [4, 31, 31]]
The second list is :
[[42, 16, 12], [42, 8, 12], [31, 7, 10]]
The two matrices don't contain common elements

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

解释

  • 定义了两个列表列表,并在控制台上显示。

  • 一个变量被设置为布尔值“True”。

  • 迭代第一个列表,并将一个临时变量设置为布尔值“False”。

  • 如果该元素存在于第二个列表中,则将临时变量设置为布尔值“True”。

  • 控制跳出循环。

  • 如果循环外部的临时变量为 False,则控制跳出循环。

  • 最后,根据临时变量的值,在控制台上显示相关消息。

更新于: 2021年9月14日

172 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告