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 情侣签名简短英文祝福语