Python - 测试所有行是否包含与其他矩阵的任何公共元素
当需要测试所有行是否包含与其他矩阵的任何公共元素时,使用简单迭代和标志值。
示例
下面是相同的演示
my_list_1 = [[3, 16, 1], [2, 4], [4, 31, 31]]
my_list_2 = [[42, 16, 12], [42, 8, 12], [31, 7, 10]]
print("第一个列表是:")
print(my_list_1)
print("第二个名单是:")
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")输出结果第一个列表是: [[3, 16, 1], [2, 4], [4, 31, 31]] 第二个名单是: [[42, 16, 12], [42, 8, 12], [31, 7, 10]] The two matrices don't contain common elements
解释
定义了两个列表列表并显示在控制台上。
变量设置为布尔值“True”。
迭代第一个列表并将临时变量设置为布尔值“False”。
如果该元素出现在第二个列表中,则临时变量设置为布尔值“True”。
控制跳出循环。
如果临时变量在循环外为False,则控制跳出循环。
最后,根据临时变量的值,在控制台上显示相关信息。
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短