确定字符串列表中的条件

Determine condition in list of strings

我习惯了 C# 和编写 python 脚本。我想确定列表中的任何字符串是否包含字符串 "ERROR".

在 C# 中我会这样做:

string myMatch = "ERROR";
List<string> myList = new List<string>();
bool matches = myList.Any(x => x.Contains(myMatch));

我在 python 中的尝试告诉 returns TRUE 即使该列表包含包含单词 ERROR.

的字符串
def isGood (linesForItem):
    result = True;
    if 'ERROR' in linesForItem:
        result = False
    return result

听起来你的意思是:

def isGood(linesForItem):
    result = True
    if any('ERROR' in line for line in linesForItem):
        result = False
    return result

或更简单地说:

def isGood(linesForItem):
    return not any('ERROR' in line for line in linesForItem)

问题是您必须检查列表中每个元素的 'ERROR' 子字符串是否存在。目前,您只需检查该字符串是否在数组中。这一行会给你答案。

any(map(lambda o: 'ERROR' in o, linesForItem))
  • True - 如果 linesForItem 列表中至少有一个元素包含 'ERROR' 子串
  • False - 否则

然后像这样将它包装在你的函数中:

def isGood(linesForItem)
    return not any(map(lambda o: 'ERROR' in o, linesForItem))

我假设 'ERROR' 嵌入在文本字符串中,并且列表中的所有项目都是文本字符串。有几种方法可以做到这一点,这是我最喜欢的:

myList = ['stuff', 'xxxxERRORxxxx', '42']

if any([s.find('ERROR') > -1 for s in myList]):
    result = True
else:
    result = False

find 方法 returns 字符串开始的位置,如果不存在则为 -1。

有时无聊的解决方案也是最快的解决方案之一...

def isGood(linesForItem):
    for line in linesForItem:
        if "ERROR" in line:
            return False
    return True

这也会在找到匹配项后立即停止。