gpt4 book ai didi

python - 复杂复合 bool 表达式

转载 作者:行者123 更新时间:2023-12-01 00:10:50 26 4
gpt4 key购买 nike

我知道如何测试多个 bool 条件(如下所示),但我想知道是否可以通过将变量分组在一起来组合测试多个 bool 条件,如下所示?有没有一种方法可以以易于理解的方式缩短工作但复杂的复合 bool 条件(版本 1)?

(在我的真实代码中,实际的测试字符串在运行时会有所不同,并且是变量)。

示例:

AnimalString = 'We were looking for a mouse in our house.'
s = AnimalString

# 1) WORKS if-statement, but very long.
if 'dolphin' in s or 'mouse' in s or 'cow' in s:
print('1: At least one listed animal is in the AnimalString.')

# 2) DOESN'T WORK Desired complex compound boolean expression
if ('dolphin' or 'mouse' or 'cow') in s:
print('2: At least one listed animal is in the AnimalString.')

# 3) DOESN'T WORK Desired complex compound boolean expression
if 'dolphin' or 'mouse' or 'cow' in s:
print('3: At least one listed animal is in the AnimalString.')

根据 SO 帖子,我知道为什么版本 2),3) 不起作用 - herehere :

  • 版本 2) 返回 bool 表达式结果为 True or True or False ,这会错误地打印消息。
  • 版本 3) 仅测试字符串 'dolphin'在 AnimalString 中并且不给出任何输出。

附加问题:也许有什么想法可以以更干净的方式解决这个问题吗?没有any() ,只是元组/列表和运算符...

接受的解决方案:查看评论、答案和文档,这似乎是最好的解决方案:
any(item in AnimalString for item in ['dolphin', 'mouse', 'cow'])

最佳答案

我不确定我是否正确理解了这个问题,但我会给你一些我过去在复杂条件下使用的模式。

您可以使用的一种方法是函数 any,它允许您定义多种可能性的复杂逻辑,并为该条件提供动态输入。如果迭代器中的任何元素为 True,则该函数将返回 True。这允许您将值与值集合进行比较,甚至将集合与其他值集合进行比较。这是一个例子:

AnimalString = 'We were looking for a mouse in our house.'
AnimalList = [ 'dolphin', 'mouse', 'cow' ]

if any( p in AnimalString for p in AnimalList ):
print('At least one listed animal is in the AnimalString.')

如果你需要匹配的值,你可以使用next,如果你希望所有元素的条件都为True,你可以使用all,它们的工作方式与 any 类似。这些函数的示例:

AnimalMatch = next(( p for p in AnimalList if p in AnimalString ), None )
if AnimalMatch is not None:
print('"%s" is in AnimalString.' % AnimalMatch)

if not all( p in AnimalString for p in AnimalList ):
print('Not all animals are contained in AnimalString.')

处理大逻辑条件(有时很复杂)的另一种方法是使用 setdict。这允许您以高性能的方式检查值的集合(因为您正在使用散列),允许匹配大量的值,甚至允许不同的输出(在 dict)。这是示例:

# Example with set  
AnimalStringSet = set( AnimalString[:-1].lower().split() ) # preprocessing
if 'mouse' in AnimalStringSet:
print('At least one listed animal is in the AnimalString.')

# Example with dict
AnimalSoundsDict = { 'dolphin': 'click', 'mouse': 'squeak', 'cow': 'moo' }
if 'mouse' in AnimalSoundsDict:
print('The "%s" sounds like "%s"' % (Animal, AnimalSoundsDict[Animal]))
else:
print('Animal "%s" not found' % Animal)

此方法可能需要一些预处理,但在必须处理大量值的情况下,这可能是值得的。

最后,对于字符串,您始终可以使用正则表达式或库 re 中的正则表达式,但更容易使代码难以阅读。示例:

AnimalRegEx = '|'.join(AnimalList) # 'dolphin|mouse|cow'
if re.search(AnimalRegEx, AnimalString) is not None:
print('At least one listed animal is in the AnimalString.')

您还可以将最后两种方法与第一种方法结合起来。

关于python - 复杂复合 bool 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59642271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com