Python - 如果列表中的任何元素在行中

标签 python list file string-matching any

所以我这里有一些代码:

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 文件。

谢谢, 尼克。

最佳答案

What I want is for each line which matches an element in 'Fly' to be outputted into 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])

关于Python - 如果列表中的任何元素在行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35361114/

相关文章:

python - 在 pygame 中执行 for 循环后,图像不会保留在屏幕上

c# - 将 IEnumerable 转换为属性列表

linux - 带有文件 io Hook 的假 linux 文件

python - Camelot Pdf 提取失败解析

python - 带有python请求库的zomato api请求

python - 使用keras的句子相似度

python - 如何确定 Python 中数字列表的趋势

R 将列出的矩阵中的行附加到矩阵/数据帧,同时跳过缺失值

swift - 在主 bundle 的子目录中查找文件时获取nil

java - 如何从文本文件中获取值