我需要使用循环编写代码,以找出两个列表中是否存在任何公共元素。所以,我写了以下内容:
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")
但是,我得到的输出是这样的:
Enter a list: [1,34,543,5,23,"apple"]
Enter another list: [54,23,6,213,"banana"]
Overlapped
Separated
由于列表中确实有一个公共成员,因此只能打印“重叠”,但最终也要打印“分离”。
该如何解决? 我正在使用python 3.7
非常感谢您!
答案 0 :(得分:1)
创建元组列表SELECT
,并使用单个(i, j)
循环遍历元组列表。因此,要么输出为for
并中断循环,要么执行"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")
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
答案 1 :(得分:0)
由于您需要打破两个循环,else
才能按预期工作,所以我认为不使用{{1} }。如果您在函数中定义代码,则可以使用else
来同时退出两个循环。
例如:
return
示例:
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()