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 妈妈生日祝福语简短励志