【问题标题】:[Python]: When would you use the `any(x)` function?[Python]:你什么时候会使用 `any(x)` 函数?
【发布时间】:2015-03-29 05:00:13
【问题描述】:

当我遇到一个我不知道的内置函数时,我正在阅读 Python 3.4 手册。函数是any(x)

Python 手册中说这个函数“如果 iterable 的任何元素为 true,则返回 True。如果 iterable 为空,则返回 False。”

他们还编写了与此功能等效的代码。

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

这个函数有什么用?

【问题讨论】:

  • 通常你会在某种条件下使用它,例如:if any(i % 2 == 0 for i in some_list_of_numbers) - 看看是否有任何偶数......
  • 如果你理解 Python 中的what is true and false 也会很有用。

标签: python python-3.x cpython any


【解决方案1】:

例如,您可以使用它来避免多个类似的情况。

要检查字符串是否包含子字符串列表,您可以这样做:

str = 'Your cat is hungry.'

if 'cat' in str:
    print 'Feed it!'
elif 'dog' in str:
    print 'Feed it!'
elif 'hamster' in str:
    print 'Feed it!'

...或者你可以这样做:

str = 'Your cat is hungry.'
pets = ['cat', 'dog', 'hamster']

if any(animal in str for animal in pets):
    print 'Feed it!'

更新:if element: return True

你是对的 - 如果迭代中的元素有一个值,它是True。在 Python 中,基本上如果变量有值,它就是True - 显然,只要值不是False。运行该示例并查看值和条件,也许它比解释更有帮助:

x = ' '
y = ''
z = False

if x:
    print 'x is True!'
else:
    print 'x is False!'

if x == True:
    print 'x is True!'
else:
    print 'x is False!'

if y:
    print 'y is True!'
else:
    print 'y is False!'    

if z:
    print 'z is True!'
else:
    print 'z is False!'      

现在回到any():它将任何可迭代对象(如列表)作为参数 - 如果该可迭代对象的任何值为True(因此得名),any() 返回True

还有一个名为 all() 的函数 - 它类似于 any(),但仅当迭代的 所有 值为 true 时才返回 True:

print any([1, 2, False])

print all([1, 2, False])

真假

@Burhan Khalid 之前在评论中提到过,但这里也应该提到关于什么被认为是 False 的官方文档:

Truth Value Testing

【讨论】:

  • 感谢您的回答。我仍然对我的问题if element: return True 的第二部分感到困惑。问题是这段特定的代码是什么意思。它的表述方式似乎是如果元素有一个值,则返回 True。
【解决方案2】:

如果你喜欢物理学,python 中的 any 函数就像电路中开关的并联连接。 如果任何一个开关打开,(if element)电路将完成,它会点亮一个串联连接的灯泡。

让如图所示的灯泡并联作为电路和 灯泡作为指示灯泡(任意的结果)

对于一个实例,如果你有一个 True 和 False 的逻辑列表,

logical_list = [False, False, False, False]
logical_list_1 = [True, False, False, False]

any(logical_list)
False  ## because no circuit is on(True) all are off(False)

any(logical_list_1)
True  ## because one circuit is on(True) remaining three are off(False)

或者你可以认为它是AND的连接,所以如果迭代器的任何一个值为False,则Result将为False。

对于字符串,场景相同,只是含义有所不同

'' empty string            -> False
'python' non empty string  -> True

试试这个:

trial_list = ['','','','']
trial_list_1 = ['python','','','']

any(trial_list)
False ## logically trial_list is equivalent to [False(''), False(''), False(''), False('')]

any(trial_list_1)
True ## logically trial_list_1 is equivalent to [True('python'), False(''), False('') , False('')]

对于单个非空字符串的情况,任何(非空字符串)总是 True 对于单个空字符串 any(空字符串总是 False

any('')
False

any('python')
True

希望对你有帮助,,

【讨论】:

  • 感谢您的回答。当您写“如果迭代器的任何一个值为 False,则结果将为 False”时,我开始思考。这对字符串意味着什么。我知道 any(x) 函数可以用于字符串,那么在处理字符串时实现 True 的标准是什么。
猜你喜欢
  • 2014-07-06
  • 1970-01-01
  • 2012-08-14
  • 2010-09-19
  • 2012-04-23
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多