【问题标题】:I'm writing a for loop with an if statement inside it but it returns nothing?我正在编写一个带有 if 语句的 for 循环,但它什么也不返回?
【发布时间】:2020-09-17 11:18:44
【问题描述】:

我正在尝试查找两个不同数组中是否存在共享元素,我编写了以下代码,但它没有返回任何内容。

    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

【问题讨论】:

  • 你运行你的代码了吗?如果是,输出是什么?

标签: python python-3.x list for-loop if-statement


【解决方案1】:

您正在迭代列表,而不是列表中的值。也不需要一次遍历两个列表。

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

【讨论】:

    【解决方案2】:

    这样做

    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)
    

    【讨论】:

    • 你做for value in gradelist1:,在循环的第一行你问if value in gradelist1。您希望如何从这些语句之间的列表中删除当前值?
    【解决方案3】:

    您的代码应如下所示:

     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
    

    【讨论】:

    • 此代码不会运行,因为for value1,value2 in (gradelist1, gradelist2) 会引发错误。它还将始终评估True,因为您正在检查该值最初来自的列表。
    猜你喜欢
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多