Skip to main content
 首页 » 编程设计

python之一个类轮 : Find if string is in list of strings

2025年05月04日91jillzhang

我正在寻找一个 bool 单行代码来查看特定子字符串是否在字符串列表中。这样我就可以在类似的地方使用它

if( (condition1) and (condition2) and (python_one_liner) ): 
  # Do some things here 

这有望取代类似的东西:

if( (condition1) and (condition2) ): 
  Condtion3 = False 
  for str in list_of_strings: 
    if( mystr in str ): 
    Condition3 = True 
 
  if( Condition3 ): 
    # Do some things here 

一个明显的方法是简单地编写一个函数并在初始的 if 语句中评估该函数。我想知道是否有更好的方法来做到这一点。

请您参考如下方法:

使用 any() function连同生成器表达式:

if condition1 and condition2 and any(mystr in s for s in list_of_strings): 

这比您的版本更有效,因为只有来自 list_of_strings 的足够 s 值被测试,直到找到第一个 True 值。

如果你还需要知道匹配的什么字符串,你可以得到第一个这样的字符串:

match = next((s for s in list_of_strings if mystr in s), None) 
if condition1 and condition2 and match: 

哪里next() function将生成器表达式迭代到第一个匹配项并返回它,或者如果没有匹配的字符串则返回 None。