python - Python 中的 `in` 运算符是否可以用于检查序列中的成员资格?

标签 python python-3.5

Python 中的

in 运算符是一个成员运算符,用于测试序列中的成员资格。

in 运算符的说明

Evaluates to true if it finds a variable in the specified sequence and false otherwise.

现在考虑代码:

>>>s = 'HELLO'
>>>char = 'M'
>>>char in s
False
>>>for char in s:
....    print(char)
H
E
L
L
O

请在这里纠正我: 我认为语句 for char in s 应该检查 'HELLO' 中的 'M' 应该评估为 False 并且应该终止循环。但是在这里,它不是检查成员资格,而是将每个字符分配给变量 char,因此循环打印每个字符。 我的问题是,除了检查成员资格之外,如何使用 in 运算符?

最佳答案

in 关键字用于两种不同的上下文:

  • 成员(member)测试
  • 迭代

第一个,如您所说,通过调用序列的 __contains__ 来检查某物是否属于序列.使用此语法时,会返回一个 bool 值。

x = 1
l = [0, 1, 2]
if x in l:
    print("x is in l")
else:
    print("x is not in l")
> x is in l

Since in looks for the __contains__ method, x in seq is valid as long as seq implements a __contains__ method. You can implement this, even though it does not make logical sense, regarding the concept of membership.

class Foo:
    def __contains__(self, x):
        return x == 12

f = Foo()
if 12 in f:
    print("12 is in f")
> 12 is in f

The second is actually more often used. According to an iteration protocol, it enumerates the elements of an iterable object, so that actions can be performed on them.

You can iterate over a list:

l = [0, 1, 2]
for x in l:
    print(x)
> 0
> 1
> 2

Over a string:

s = "hello"
for c in s:
    print(c)
> h
> e
> l
> l
> o

And over any object implementing the __iter__ method, as long as the latter returns an object that implements the __next__ method.

The following example is a basic (not to say "poor") range-like class, whose you can iterate over the instances.

class Bar:
    def __init__(self, first, last):
        self.first = first
        self.last = last
        self.current = first

    def __iter__(self):
        return self

    def __next__(self):
        if self.current == self.last:
            raise StopIteration
        result = self.current
        self.current += 1
        return result

b = Bar(0, 5)
for i in b:
    print(i)
> 0
> 1
> 2
> 3
> 4

很多原生类型都是可迭代的:dictionaries , ranges , sets ...


从语义上讲,在两种上下文中使用相同的 in 词是有意义的。 “那个东西里有这个东西吗?”是一个有效的问题,只要“东西”是一个能够包含东西的集合。从今以后,“对那些东西中的每一件事都这样做”似乎很自然。

因此在这两种情况下都使用“in”。

然而,这是对现实的相当简化,而现实实际上更为广阔。我邀请您阅读 documentation , 要深入了解 in 关键字,请阅读 Python's grammar .

关于python - Python 中的 `in` 运算符是否可以用于检查序列中的成员资格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41741317/

相关文章:

python - 保留/切片 Pandas 中的特定列

python - 更新 panda 中的整个 Excel 行

python - 无法在 Windows XP Professional 中安装 Python 3.5

python3导入错误: while running with sudo -u <user> python3

python - 单击传单 Web 应用程序后如何将纬度和经度返回到 Flask 服务器?

python - 使用 Pandas 将多行转换为单行

python - 在python中按列表的顺序重复选择n项

python - 如何在 Python 中使用 M2Crypto 重新创建以下签名 cmd 行 OpenSSL 调用?

python - ProcessPoolExecutor 和 ThreadPoolExecutor 有什么区别?

python - 类型提示、与前向引用的联合