在python中使用"if all"

a12*_*773 2 python beautifulsoup

为什么这个工作

for td in alltd:
    if "style3" in td["class"] or "style4" in td["class"] or "style1" in td["class"]:
        td["class"] = "s1"
Run Code Online (Sandbox Code Playgroud)

这不是吗?

for td in alltd:
    if all(x in td["class"] for x in ("style3", "style4", "style1")):
        td["class"] = "s1"
Run Code Online (Sandbox Code Playgroud)

Mat*_*ams 11

all([x1,x2,...])基本上是一样的x1 and x2 and ...,不是x1 or x2 or ...

>>> all([True, True])
True
>>> all([True, False])
False
Run Code Online (Sandbox Code Playgroud)

any()改用.

>>> any([True,False])
True
Run Code Online (Sandbox Code Playgroud)


Ash*_*ary 6

使用any()如果你正在做or基于comaparison:

`if any(x in td["class"] for x in ("style3", "style4", "style1")):`
Run Code Online (Sandbox Code Playgroud)

任何(可迭代的)帮助:

如果iterable的任何元素为true,则返回True.#即or条件

帮助所有(可迭代):

如果iterable的所有元素都为true,则返回True.#即and汇款