【问题标题】:how to get the variable from an any() function如何从 any() 函数中获取变量
【发布时间】:2019-11-28 20:33:07
【问题描述】:

我正在寻找满足条件的 list_select 变量,并在下一行进行追加。

我怎样才能使它在 list_select.append(dupe) 行中可用?

if any(list_select in dupe for list_select in pattern_dict):
   list_select.append(dupe)

【问题讨论】:

  • 你能举个例子吗?也许你应该写一个普通的for循环。

标签: python any


【解决方案1】:

你不能使用any,它只返回一个布尔值。改用生成器表达式:

gen = (x for x in pattern_dict if x in dupe)
list_select = next(gen, None)
if list_select is not None:
    ...

【讨论】:

    【解决方案2】:

    any 函数应该返回一个布尔值,因此如果您想要返回第一个匹配项的行为略有不同,请编写一个具有该行为的函数:

    def first(seq):
        return next(iter(seq), None)
    

    用法:

    >>> first( i for i in range(10) if i**2 > 10 )
    4
    >>> first( c for c in 'Hello, world!' if c.islower() )
    'e'
    >>> first( i for i in range(10) if i == 100 ) is None
    True
    

    要在您的示例中使用,您可以编写如下内容:

    list_select = first( x for x in pattern_dict if x in dupe )
    if list_select is not None:
        list_select.append(dupe)
    

    如果您使用的是 Python 3.8 或更高版本,可怕的"walrus" operator 允许更直接的解决方案:

    if any((list_select := x) in dupe for x in pattern_dict):
        list_select.append(dupe)
    

    这种情况恰好是one of the motivating examples介绍海象算子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多