-1

我需要从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”,这是正确的。问题是我还需要检查一些没有公共元素和输出 [] 的列表,这里出错了。我的错误是什么?谢谢你。

4

3 回答 3

1

请注意,return将退出该函数,因此您只想在if语句中有一个。还检查成员身份sets将更快:

def find_common(L1,L2):
    s2 = set(L2)
    for element in L1:
        if element in s2:
            return element
    else:
        return []

find_common(L1, L2)
# ['Computers']
于 2019-10-16T12:10:04.113 回答
0

你好 你得到 [ ] 是正常的,因为 return 会破坏(退出)你的代码

 def find_common(L1,L2):
     for element in L1:
        if element in L2:
           print(element)

如果你想从你的代码中得到一个相似词的列表,你必须初始化一个空列表,你填写你的循环

 def find_common(L1,L2):
     Similar = []
     for element in L1:
        if element in L2:
           Similar.append(element)
     return Similar
于 2019-10-16T12:15:32.457 回答
0

Your function find_common returns [] already if only one of the elements in L1 is not present in L2. Therefore you should only return [] if none of the elements in L1 are in L2, that is when you ran through the whole loop:

def find_common(L1,L2):
   for element in L1:
        if element in L2:
            return (element)
   return []
于 2019-10-16T12:15:45.883 回答