使用集合输出两个列表的公共元素

Output Common Elements of Two Lists using Sets

我想编写一个函数定义,它接受两个列表和 returns 一个具有每个列表共有值的集合。

正式地,这里有一些我想通过的断言:

assert get_values_in_common([5, 1, 2, 3], [3, 4, 5, 5]) == {3, 5}
assert get_values_in_common([1, 2], [2, 2, 3]) == {2}
assert get_values_in_common(["tomato", "mango", "kiwi"], ["eggplant", "tomato", "broccoli"]) == {"tomato"}

这是我遇到问题的代码:

def get_values_in_common(x, y):
    list = ""
    for a in x:
        if a in x and a in y:
            list.append(a)
    return list

我收到一个错误输出,我知道它与字符串和整数有关,但我不确定到底是什么问题。 (也许是我通过说 list = "" 来制作上面的列表?):

AttributeError: 'str' object has no attribute 'append'

如果你想使用 append() 那么你必须使用列表

 list = []

如果你使用字符串list = ""那么你只能连接字符串

 list = list + str(a)

但是您需要 set 作为答案,那么您应该使用 list = set()add(a)

def get_values_in_common(x, y):
    result = set()

    for a in x:
        if a in y: # there is no need to check `if a in x`
            result.add(a)

    return result

但你也可以缩短时间

def get_values_in_common(x, y):
    return set(x) & set(y)

这就是 set() 非常有用的原因。