将列表与文件行进行比较

时间:2015-08-10 14:30:31

标签: list file python-3.x

我正在尝试将列表与从文本文件中读取的行进行比较。我问了一个类似的问题here,但这不起作用,因为数据是从文件中读取的,每行都是分开的。

Assme数据文件看起来像

2 3 5
1 2 7 8 2
1 4 3 4 6

我使用

读取该文件
fs = open("in.txt")
lines = [line.split() for line in fs if line.strip()]

然后,我定义了一个像这样的列表

seen = []
seen.append(1)
seen.append(2)

接下来,我将队列与每一行进行比较,以便使用

查找匹配项
take = [row for row in lines if row[:2] == seen]

然而,虽然它应该是1 2 7 8 2,但是它是空的。完整的代码是

fs = open("in.txt")
lines = [line.split() for line in fs if line.strip()]
seen = []
seen.append(1)
seen.append(2)

take = [row for row in lines if row[:2] == seen]
if len(take) != 0:
    print(take)
else:
    print("no match")

在调试程序时,我发现文件的每一行都显示为['1', '2', '7', '8', '2']seen列表看起来像[1 2]。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

当您在列表中读取输入文件时,列表的内容是字符串..您只需键入cast每个条目...

fs = open("in.txt")
lines = [[int(strNumber) for strNumber in line.split()] for line in fs if line.strip()]

其余应该类似.. 如果内容不能转换为整数,也许你也应该处理异常..

相关问题