![](/img/trans.png)
[英]How does the select() function in the select module of Python exactly work?
[英]How exactly does the python any() function work?
在any
python文檔頁面中, any()
函數的等效代碼如下:
def any(iterable):
for element in iterable:
if element:
return True
return False
如果以這種形式調用它,這個函數如何知道我想測試哪個元素?
any(x > 0 for x in list)
從函數定義中,我只能看到我傳遞的是一個可迭代對象。 for
循環如何知道我正在尋找> 0
東西?
如果您使用any(lst)
您會看到lst
是可迭代的,這是一些項目的列表。 如果它包含[0, False, '', 0.0, [], {}, None]
(它們都具有False
布爾值)那么any(lst)
都將為False
。 如果lst
還包含以下任何一個[-1, True, "X", 0.00001]
(所有值都為True
),那么any(lst)
都將為True
。
在您發布的代碼中, x > 0 for x in lst
, x > 0 for x in lst
,這是一種不同的可迭代類型,稱為生成器表達式 。 在將生成器表達式添加到Python之前,您將創建一個列表推導 ,它看起來非常相似,但周圍的[]
: [x > 0 for x in lst]
。 從包含[-1, -2, 10, -4, 20]
lst
中,你會得到這個被理解的列表 : [False, False, True, False, True]
。 然后,此內部值將傳遞給any
函數,該函數將返回True
,因為至少有一個True
值。
但是使用生成器表達式 ,Python不再需要創建True(s)
和False(s)
內部列表,當any
函數迭代生成器表達式一次生成的值時,將生成這些值。 並且 ,由於any
短路,一旦看到第一個True
值,它就會停止迭代。 如果你使用類似lst = range(-1,int(1e9))
(或xrange
如果你使用Python2.x )創建lst
這將特別方便。 即使這個表達式將生成超過十億個條目, any
只有當它達到1
時才必須到第三個條目,它會為x>0
計算True
,因此any
都可以返回True
。
如果您已經創建了列表解析 ,那么Python首先必須在內存中創建十億元素列表,然后將其傳遞給any
。 但是,通過使用一台發電機的表情 ,你可以有Python的內置功能,如any
和all
只要一個早期的爆發, True
或False
的值為止。
>>> names = ['King', 'Queen', 'Joker']
>>> any(n in 'King and john' for n in names)
True
>>> all(n in 'King and Queen' for n in names)
False
它只是將幾行代碼減少為一行。 您不必編寫冗長的代碼,例如:
for n in names:
if n in 'King and john':
print True
else:
print False
(x > 0 for x in list)
中的(x > 0 for x in list)
在該函數調用中創建一個生成器表達式,例如。
>>> nums = [1, 2, -1, 9, -5]
>>> genexp = (x > 0 for x in nums)
>>> for x in genexp:
print x
True
True
False
True
False
遇到第一個評估True
對象的any
用途和短路
這是因為可迭代的
(x > 0 for x in list)
請注意, x > 0
返回True
或False
,因此您有一個可迭代的布爾值。
簡單地說,any()可以做到這一點:根據條件,即使它在列表中遇到一個滿足的值,它返回true,否則返回false。
list = [2,-3,-4,5,6]
a = any(x>0 for x in lst)
print a:
True
list = [2,3,4,5,6,7]
a = any(x<0 for x in lst)
print a:
False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.