【问题标题】:Python - If any element in list is in linePython - 如果列表中的任何元素在行
【发布时间】:2016-02-12 11:10:00
【问题描述】:

所以我这里有一些代码:

for line in FlyessInput:
if any(e in line for e in Fly):
    FlyMatchedOutput.write(line)
elif line not in Fly:
    FlyNotMatchedOutput.write(line)
else:
    sys.exit("Error")

由于某种原因,它们不会输出列表“Fly”中匹配的行,而是仅输出出现在 FlyessInput 文件中的行,而不是全部。它似乎没有一致的输出。

我想要的是将与“Fly”中的元素匹配的每一行输出到 FlyMatchedOutput。我检查了输入文件和“Fly”列表,有一些匹配的元素,但它们似乎没有发送到 MatchedOutput 文件。

谢谢, 尼克。

【问题讨论】:

    标签: python list file string-matching any


    【解决方案1】:

    我想要的是将与“Fly”中的元素匹配的每一行输出到 FlyMatchedOutput。

    我不认为你的 elif 做你认为应该做的事,但不知道你的测试输入我不能说这是否会导致问题。

    这里对您的代码稍作改动,似乎可以满足您的需求(尽管是 priting 而不是调用您的其他函数。

    def testFlyCode(FlyessInput, Fly):
        for line in FlyessInput:
            if any(e in line for e in Fly):
                print('FlyMatchedOutput', line)
            else:
                print('FlyNotMatchedOutput', line)
    
    FlyessInput = [[1, 2, 3], [2, 3, 4]]
    Fly = [1, 2]
    testFlyCode(FlyessInput, Fly)
    
    Fly = [1, 12]
    testFlyCode(FlyessInput, Fly)
    

    输出:

    ('FlyMatchedOutput', [1, 2, 3])
    ('FlyMatchedOutput', [2, 3, 4])
    ('FlyMatchedOutput', [1, 2, 3])
    ('FlyNotMatchedOutput', [2, 3, 4])
    

    【讨论】:

      猜你喜欢
      • 2012-10-10
      • 1970-01-01
      • 2015-04-16
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      相关资源
      最近更新 更多