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 教师闺蜜祝福语简短