我知道这个问题太基本了,但我无法理解。
例如,如果必须搜索字符串中的任何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,即使有一个单词匹配,不管它在哪个索引中
假设我们要计算
a or b
。or
操作符的工作方式如下:a
是truthy,则返回a
b
李>如果有两个以上的操作数,例如
a or b or c or d
,则它相当于a or (b or (c or d))
,因此它将根据以下算法工作:a
是truthy,则返回a
b
是truthy,则返回b
c
是truthy,则返回c
d
李>所以这个表达式:
('browser' or 'chrome') in 'start chrome'
将不会像您期望的那样工作。首先,('browser' or 'chrome')
将计算为'browser'
(因为'browser'
和任何非空字符串一样是真实的,'browser' in 'start chrome'
是False
您可能希望使用的是:
或者您可以使用
any
,并结合生成器:或者,如果你真的喜欢
map
基本上,
any
返回True
,如果给定iterable的至少一个元素是truthy
a and b and c
的工作原理与or
类似: 1.如果a
为false,则返回a
1.否则,如果b
为false,则返回b
1.否则,返回c
您可能希望使用以下内容来代替
and
-y表达式:或者您可以使用
all
,它类似于any
,但实现了and
-logic或者or
-logic:https://docs.python.org/3/library/functions.html#all可能有两种方法可供选择: 一种简单、不太动态的方法:
更长但更具活力的方法:
('browser' or 'chrome')
的计算结果为'browser'
见How do “and” and “or” act with non-boolean values?
您可以使用the ^{} function :
和the ^{} function :
相关问题 更多 >
编程相关推荐