问题描述
我试图查找两个不同数组中是否存在共享元素,我编写了以下代码,但未返回任何内容。
gradelist1 = [1,3,5]
gradelist2 = [1,4,7]
for value in (gradelist1,gradelist2):
if value in gradelist1 and value in gradelist2:
print('The value occurs in both the lists')
break
解决方法
您要遍历列表,而不是遍历列表中的值。同样,也不需要一次遍历两个列表。
gradelist1 = [1,3,5]
gradelist2 = [1,4,7]
for value in gradelist1:
if value in gradelist2:
print('The value occurs in both the lists')
break
您也可以只进行列表理解[i for i in gradelist1 if i in gradelist2]
来直接获取两个列表中的所有值。
以这种方式做
gradelist1 = [1,7]
x = [] # create a list
for value in (gradelist1):
if value in gradelist2: #first check if the value from the list1 is in the list 2
x.append(value) # add to it the values if the condition is rigth
print('the folloging numbers are inclued in both arrays')
print(x)
,
您的代码应如下所示:
gradelist1 = [1,5]
gradelist2 = [1,7]
for value1,value2 in zip(gradelist1,gradelist2):
if value1 in gradelist1 and value2 in gradelist2:
print('The value occurs in both the lists')
break