如何在python中检查字符串中的这个或那个字符?

如何在python中检查字符串中的这个或那个字符?,python,Python,当我只使用一个字符串或字符来检查字符串中出现的情况时,它工作正常,但当我使用两个字符串(“字符串中的a”或“b”)时,它就不工作了 lst =["test in a", "test in b" "test b in a", "a test b", "test"] for i in lst: if("a" or "b" in lst): print("true") else: print("false") 预期结果: true true true t

当我只使用一个字符串或字符来检查字符串中出现的情况时,它工作正常,但当我使用两个字符串(“字符串中的a”或“b”)时,它就不工作了


lst =["test in a", "test in b" "test b in a", "a test b", "test"]

for i in lst:
   if("a" or "b" in lst):
      print("true")
   else:
      print("false")
预期结果:

true

true

true

true

false
试试这个

lst =["test in a", "test in b" "test b in a", "a test b", "test"]

    for i in lst:
       if any(item in i for item in ['a', 'b']):
          print("true")
       else:
          print("false")
试试这个

lst =["test in a", "test in b" "test b in a", "a test b", "test"]

    for i in lst:
       if any(item in i for item in ['a', 'b']):
          print("true")
       else:
          print("false")

你甚至不需要括号

if "a" in i or "b" in i:

你甚至不需要括号

if "a" in i or "b" in i:

您可以使用列表理解将其压缩为一行,如下所示:

lst =["test in a", "test in b" "test b in a", "a test b", "test"]
test = [True if (("a" in i) or ("b" in i)) else False for i in lst]
我个人更喜欢在以下情况下使用lambdas:

# This is written a bit wide, my style for these sort of things
f = lambda x: True if "a" in x else True if "b" in x else False
test = [f(i) for i in lst]

您可以使用列表理解将其压缩为一行,如下所示:

lst =["test in a", "test in b" "test b in a", "a test b", "test"]
test = [True if (("a" in i) or ("b" in i)) else False for i in lst]
我个人更喜欢在以下情况下使用lambdas:

# This is written a bit wide, my style for these sort of things
f = lambda x: True if "a" in x else True if "b" in x else False
test = [f(i) for i in lst]

首先,列表中缺少逗号
。修复后,请尝试以下操作:

>>> lst =["test in a", "test in b", "test b in a", "a test b", "test"]
>>> test_set = {'a', 'b'}
>>> for text in lst :
...     print len(test_set & set(text)) > 0
... 
True
True
True
True
False

首先,列表中缺少逗号
。修复后,请尝试以下操作:

>>> lst =["test in a", "test in b", "test b in a", "a test b", "test"]
>>> test_set = {'a', 'b'}
>>> for text in lst :
...     print len(test_set & set(text)) > 0
... 
True
True
True
True
False

是的,但如果(i中的“a”或“b”)与(i中的“a”或(i中的“b”)相同,不是吗?不,这不是python中如何使用或条件,你想让它表示a或b,你基本上是在i中写a或(b)不。因为
中的优先级高于
如果“a”,你就有
或(i中的“b”)
。而
“a”
总是“真实”的,如果(i中的“a”或(i中的“b”),它不应该是吗?是的,但是如果(i中的“a”或“b”)与(i中的“a”或(i中的“b”)相同,或者不是吗?不,这不是python中的用法或条件,你想让它代表a或b,你基本上是在写a或(i中的b)否。因为
中的
中的
优先级更高,如果“a”或(“b”在i中)
。而
“a”
总是“真实的”