我正在写一个for循环,里面有一个if语句,但它什么也不返回?

2024-09-29 23:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出两个不同的数组中是否有共享元素,我编写了以下代码,但它什么也不返回

    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


Tags: andthe代码in元素forifvalue
3条回答

这样做吧

gradelist1 = [1, 3, 5]
gradelist2 = [1, 4, 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, 3, 5]
 gradelist2 = [1 ,4,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

您正在迭代列表,而不是列表中的值。此外,不需要同时迭代两个列表

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],直接获取两个列表中的所有值

相关问题 更多 >

    热门问题