Python: 在Set的.intersection()方法中自动更改要设置的字符串?

Python: Automatically change string to set in .intersection() method of Set?

我是 Python 的新手(并且具有 Java 的基础知识),目前我正在使用第 2 版《深入浅出》Python 自学它。

在书中的一个例子中,展示了如何使用Sets的.intersection()方法。它通过以下方式实现:

if __name__ == '__main__':
    def search_for_vowels(word: str) -> set:
        """Return any vowels found in supplied word."""
        vowels = set('aeiou')
        return vowels.intersection(set(word))

    print(search_for_vowels('hitch-hiker'))
    print(search_for_vowels('sky'))

然而,当我自己尝试这个时,我不小心忘记了上面代码中的 'set' 部分(打印语句上方),因此变成:

if __name__ == '__main__':
    def search_for_vowels(word: str) -> set:
        """Return any vowels found in supplied word."""
        vowels = set('aeiou')
        return vowels.intersection(word)

    print(search_for_vowels('hitch-hiker'))
    print(search_for_vowels('sky'))

但是,代码 运行 没有任何问题并返回了正确的输出。这对我来说似乎有点奇怪,因为我会将一个集合与一个字符串进行比较,而不是将一个集合与一个集合进行比较。因此我的问题是:在执行 Set 的 intersection() 方法时,Python 会自动将字符串转换为集合吗?

提前致谢, 大卫

intersection method requires an iterable作为参数。

您正在传递一个可迭代的 string(word),因此它可以成功运行。

来自 official docs, some set methods,包括 intersection(),接受 other 的迭代:

Note, the non-operator versions of union(), intersection(), difference(), symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') & 'cbs' in favor of the more readable set('abc').intersection('cbs') .

Note, the non-operator versions of the update(), intersection_update(), difference_update(), and symmetric_difference_update() methods will accept any iterable as an argument.

强调我的。可能没有发生转换(我没有检查源代码)。

操作员 vs 非操作员:

来自文档:

union (*others )
set | other | ...
Return a new set with elements from the set and all others.

intersection (*others )
set & other & ...
Return a new set with elements common to the set and all others.

所以|union()的运算符,&intersection()的运算符。

示例:

>>> # using the & operator, with a set
>>> set('abc') & set('cbs')
{'c', 'b'}
>>>
>>> # using the intersection method, with a set
>>> set('abc').intersection(set('cbs'))
{'c', 'b'}
>>>
>>> # using the & operator, with non-set (error)
>>> set('abc') & 'cbs'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'set' and 'str'
>>>
>>> # using the intersection method, with non-set (okay)
>>> set('abc').intersection('cbs')
{'c', 'b'}
>>>
>>> # also applies to general operations, see link below
>>> # using the + operator with two integers
>>> 4 + 5
9
>>> # using the __add__ method
>>> (4).__add__(5)
9

看到这个 list of operators and their methods/functions。一些内置类型,如集合和字典,也都有自己的运算符映射。使用 __dunder__(双下划线 x2)魔术方法,这些也可以为用户定义的对象实现。

非运算符版本接受任何可迭代对象作为参数。非操作员是指这些操作的功能实现,如 .intersection().union()、e.t.c.

如果要使用此操作的运算符版本,应设置所有变量。

例如 -> set1 & set2 需要两个类型集合的操作数。