python字符串中的逻辑运算符

2024-10-02 10:29:47 发布

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

我知道这个问题太基本了,但我无法理解。 例如,如果必须搜索字符串中的任何N单词,我该如何执行此操作。我尝试了逻辑运算

('browser' or 'chrome') in 'start game'

它将返回false

('browser' or 'chrome') in 'start chrome'

它会变成现实

('browser' or 'chrome') in 'start chrome'

这应该返回True,但返回falsechrome单词在字符串中,所以为什么它返回false

('browser' and 'chrome') in 'start chrome'

这是真的。但为什么它会返回true,即使只有一个单词匹配

我想返回True,即使有一个单词匹配,不管它在哪个索引中


Tags: orand字符串inbrowsergamefalsetrue
3条回答

假设我们要计算a or bor操作符的工作方式如下:

  1. 如果a是truthy,则返回a
  2. 否则,返回b

如果有两个以上的操作数,例如a or b or c or d,则它相当于a or (b or (c or d)),因此它将根据以下算法工作:

  1. 如果a是truthy,则返回a
  2. 否则,如果b是truthy,则返回b
  3. 否则,如果c是truthy,则返回c
  4. 否则,返回d

所以这个表达式:('browser' or 'chrome') in 'start chrome'将不会像您期望的那样工作。首先,('browser' or 'chrome')将计算为'browser'(因为'browser'和任何非空字符串一样是真实的,'browser' in 'start chrome'False

您可能希望使用的是:

('browser' in 'start chrome') or ('chrome' in 'start chrome')

或者您可以使用any,并结合生成器:

string = 'start chrome'
if any(substring in string for substring in ['browser', 'chrome', 'chromium']):
    print('Ta da!')

或者,如果你真的喜欢map

if any(map(string.__contains__, ['browser', 'chrome', 'chromium'])):
    print('Ta da!')

基本上,any返回True,如果给定iterable的至少一个元素是truthy

a and b and c的工作原理与or类似: 1.如果a为false,则返回a 1.否则,如果b为false,则返回b 1.否则,返回c

您可能希望使用以下内容来代替and-y表达式:

('start' in 'start chrome') and ('chrome' in 'start chrome')

或者您可以使用all,它类似于any,但实现了and-logic或者or-logic:https://docs.python.org/3/library/functions.html#all

可能有两种方法可供选择: 一种简单、不太动态的方法:

"browser" in "start chrome" or "chrome" in "start chrome"

更长但更具活力的方法:

def OneContains(l, text):
    for i in l:
        if i in text:
            return True
    return False


print(OneContains(["browser","chrome"],"start chrome"))

('browser' or 'chrome')的计算结果为'browser'

How do “and” and “or” act with non-boolean values?

您可以使用the ^{} function

if any(x in 'start chrome' for x in ('browser', 'chrome')):
    # at least one of the words is in the string 

the ^{} function

if all(x in 'start chrome' for x in ('browser', 'chrome')):
    # both words are in the string

相关问题 更多 >

    热门问题