简体   繁体   English

比较两个列表,python

[英]comparing two lists, python

I should define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. 我应该定义一个函数overlay(),它接受两个列表,如果它们至少有一个共同的成员,则返回True,否则返回False。 For the sake of the exercise, I should write it using two nested for-loops. 为了练习,我应该使用两个嵌套的for循环编写它。 What am I doing wrong? 我究竟做错了什么?

def overlapping(a,b):
    for char in a:
        for char2 in b:
            return char in char2

Any suggestions how to make it work? 有什么建议如何使其工作?

You should use == and not the in operator 您应该使用==而不是in运算符

def overlapping(list_a,list_b):
    for char_in_list_a in list_a:
        for char_in_list_b in list_b:
            if char_in_list_a == char_in_list_b:
                return True
    return False

If you want something using set: 如果您需要使用set的东西:

def overlapping(a,b):
         return bool(set(a) & set(b))

If you really need to use 2 loops: 如果您确实需要使用2个循环:

def overlapping(a,b):
    for char1 in a:
        for char2 in b:
            if char1 == char2: return True
    return False

But the solution with sets is much better. 但是带有集合的解决方案要好得多。

Return ends the function immediately when executed. Return在执行时立即结束功能。 Since this is a homework, you should figure working solution by yourself. 由于这是一项家庭作业,因此您应该自己确定可行的解决方案。 You might consider using a set. 您可能会考虑使用一套。

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

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