简体   繁体   English

使用 For-Else 执行这两个条件。 我该如何解决?

[英]Using a For-Else executes both the conditions. How do I fix this?

I need to write a code, using loops, to find out if there is any common element in two lists.我需要使用循环编写代码以找出两个列表中是否有任何公共元素。 So, I wrote the following:所以,我写了以下内容:

l1 = eval(input("Enter a list: "))
l2 = eval(input("Enter another list: "))
for i in range (len(l1)):
        for j in range (len(l2)):
                if l1[i] == l2[j]:
                        print("Overlapped")
                        break
else:
        print("Separated")

However, what I get as output is this:但是,我得到的输出是这样的:

Enter a list: [1,34,543,5,23,"apple"]
Enter another list: [54,23,6,213,"banana"]
Overlapped
Separated

Since the lists do have a common member, it should only print "Overlapped", but it ends up printing "Separated", too.由于列表确实有一个公共成员,它应该只打印“重叠”,但最终也会打印“分离”。

How do I fix this?我该如何解决? I'm using python 3.7我正在使用 python 3.7

Thank you so much!!非常感谢!!

Create a list of tuples (i, j) and use a single for loop to traverse the list of tuples.创建元组列表(i, j)并使用单个for循环遍历元组列表。 So either the output is "Overlapped" and the loop is breaks out or the else clause is executed and the output is "Separated" :因此,要么输出"Overlapped"并且循环中断,要么执行else子句并且输出"Separated"

for i, j in [(i, j) for i in range(len(l1)) for j in range(len(l2))]:
    if l1[i] == l2[j]:
        print("Overlapped")
        break
else:
    print("Separated")

Output:输出:

 Enter a list: [1,34,543,5,23,"apple"] Enter another list: [54,23,6,213,"banana"] Overlapped

 Enter a list: [1,34,543,5,23,"apple"] Enter another list: [54,234567,6,213,"banana"] Separated

Alternatively you can create a list of tuples with the indices of the equal list elements.或者,您可以创建一个具有相等列表元素索引的元组列表。 Finally check if the list is empty:最后检查列表是否为空:

equal = [(i, j) for i in range (len(l1)) for j in range(len(l2)) if l1[i] == l2[j]]
if equal:
     print("Overlapped")
else:
     print("Separated")  

Since you'll need to break out of both loops for the else to work as you expect, I think it'll be easier to just not use the else at all here.由于您需要打破两个循环才能让else像您期望的那样工作,我认为在这里根本不使用else会更容易。 If you define your code in a function, you can use return to break out of both loops at the same time.如果在函数中定义代码,则可以使用return同时跳出两个循环。

For example:例如:

def have_common_elements():
    l1 = eval(input("Enter a list: "))
    l2 = eval(input("Enter another list: "))
    for i in range (len(l1)):
        for j in range (len(l2)):
            if l1[i] == l2[j]:
                return True
    return False # will only happen if the previous `return` was never reached, similar to `else`

have_common_elements()

Sample:样本:

Enter a list: [1,34,543,5,23,"apple"]
Enter another list: [54,23,6,213,"banana"]
True

Enter a list: [1,34,543,5,25,"apple"]
Enter another list: [54,23,6,213,"banana"]
False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM