如何理解Python中的modulo in all()函数?

2024-04-24 09:36:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道Python中的模%表示获取余数,例如:

print 6 % 4            # 2, because 6 = 1 * 4 + 2
print 4 % 2            # 0, because 4 = 2 * 2 + 0

我还学到了all()函数类似于通用量化,如果所有命题都是True,它返回True,并且它的参数应该是一个itarable。你知道吗

my_list = [True, True, True, True]
print all(my_list)                    # True

但是,我仍然无法理解以下代码:

test_num = [3,6,9]

print all (11 % i for i in test_num)        # True

for unknown in (11 % i for i in test_num):
    print unknown, type(unknown)            # 2 <type 'int'>
                                            # 5 <type 'int'>
                                            # 2 <type 'int'>

那么,为什么我能从项都是整数的iterable中得到真值呢?你知道吗

谢谢你!你知道吗


Tags: 函数intesttrueformytypeall
3条回答

除0以外的任何内容都被视为真。因为test_num中没有0,all(test_num)将返回true。你知道吗

试试这个:

>>> test_num = [2,3,0]
>>> print all(test_num)
False  

对for循环应用相同的逻辑,您将得到答案。你知道吗

如果在布尔上下文中取整数(例如在条件中,或通过bool显式地),它将返回该整数是否为非零:

>>> bool(0)
False
>>> bool(43)
True

让我们看看代码:

(11 % i for i in test_num)是一个生成器,它展开到11 % 311 % 611 % 9,这些生成器会变成252。因为它们都是非零的,all返回True。你知道吗

实际上,当且仅当11既不可被3、6或9整除时,它返回True。你知道吗

你看救命书了吗?你知道吗

Help on built-in function all in module __builtin__:

all(...)
    all(iterable) -> bool

    Return True if bool(x) is True for all values x in the iterable.
    If the iterable is empty, return True.

all()处理布尔值并返回布尔值。所以整数被转换成布尔值,这意味着任何非零值都返回True。因此,如果任何模返回0,则为False,否则为True。你知道吗

>>> print all([False,True])
False
>>> print all([True,False])
False
>>> print all([True,True])
True

相关问题 更多 >