gpt4 book ai didi

python - all()函数的正确用法

转载 作者:行者123 更新时间:2023-11-28 21:55:15 26 4
gpt4 key购买 nike

如何在 python 中使用 all() 函数?看了网站的文档,还是不太明白是怎么用的。

例子:

>>> a = '----'
>>> b = '--e'
>>> all(a) is '-'
False
>> all(b) is not '-'
True
>>> all(a) is not '-'
True
>>> all(b) is '-'
False

我预计上述所有示例的结果都是相反的。

比如说,我想写一个 if 语句来检查所有 char 是否是 some_str 是一个 '-'。如果 some_str 包含所有'-',则返回打印语句“所有破折号”

some_str = '-------'
if all(some_str) is '-':
print("all dashes")
elif all(some_str) is not '-':
print("not all dashes")

即使我在 some_str 中添加了一个非“-”,上面例子的结果总是“不全是破折号”

如何使上述 if 和 elif 语句起作用?

最佳答案

all 需要一个可迭代对象,所以让我们给它一个:

>>> all(c=='-' for c in '-------')
True
>>> all(c=='-' for c in '------x')
False

all(...) 将始终为 TrueFalse,永远不会 "-",这就是为什么您的示例无法运行的原因。

关于python - all()函数的正确用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22976642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com