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

标签 python function python-3.x

如何在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/

相关文章:

Python MVC 风格的 GUI 温度转换器

python - 如何将 "textbox"中的文本添加到图像中?

python - 如何从 csv 文件中读取 python 中的数字?

python - 动态填充 python 字典

c++ - 在 C++ 中使用默认参数时重载函数的实例不止一次

c++ - 是否有一个函数结合了 kbhit() 和 getch() 函数?

python - 在 get_queryset 中返回一个 Http 响应

python - PyCharm 卡在 'scanning files to index' 后台任务上

python - 简单功能不起作用,看不到错误

python - Django的TypeError : the first argument must be callable when I import a scheduler in my views. py文件?