我需要从2个列表中找到共同的元素,如果没有,打印[]。我设法完成了第一部分,但是当我添加其他内容时,它会横向...
def find_common(L1,L2):
for element in L1:
if element in L2:
return (element)
else :
return []
L1 = ['Dancing', 'Computers', 'Rowing']
L2 = ['Computers', 'Books', 'Movies']
print(find_common(L1,L2)) #should print "Computers"
L1 = ['Fishing']
L2 = ['Swimming']
print(find_common(L1,L2)) #should print []
此代码的输出现在是 [][]。如果我不添加else函数,则输出为“Computer”,这是正确的。问题是我还需要检查一些没有公共元素和输出 [] 的列表,这里出错了。我的错误是什么?谢谢你。