如何在python中将文件读入列表?

时间:2015-09-11 21:24:55

标签: python file

我有一个以空格分隔的文件 例如。

1 1 2
1 2 3
2 2 3
1 1 3

我想将每一行放入一个列表中,从而创建一个列表列表。我想省略文件的第一列,我想将类型转换为Integer,以便我可以对它执行整数操作。因此,关于示例的列表应该看起来像[[1,2],[2,3],[2,3],[1,3]] 我使用的代码如下所列。

class Graph:
    def __init__(self):
        f = open("Ai.txt")
        next(f)
        self.coordinates = []
        count = 0
        for line in f:
            if count == 274:
                break
            else:
                self.coordinates.append([ int(i) for i in line.split()[1:] ])
                count += 1


    def getLocation( self, vertex ):
        return self.coordinates[vertex]

g = Graph()
x = g.getLocation(44)
print x

4 个答案:

答案 0 :(得分:3)

with open('/path/to/file') as f:
    x = [[int(i) for i in l.split()[1:]] for l in f if l.strip()]
print(x)
# Outputs: 
# [[1, 2], [2, 3], [2, 3], [1, 3]]

答案 1 :(得分:3)

zip(*zip(*csv.reader(open("my_file.txt"),delimiter=" "))[1:])

如果你需要整数,你可以将它包装在一些地图中

map(lambda x:map(int,x),zip(*zip(*csv.reader(open("my_file.txt"),delimiter=" "))[1:]))

答案 2 :(得分:0)

a = """1 1 2
1 2 3
2 2 3
1 1 3"""

result = [map(int,line.split(" ")[1:]) for line in a.split("\n")]
print(result)

输出:

[[1, 2], [2, 3], [2, 3], [1, 3]]

PS:我让你处理文件部分:P

希望这会有所帮助:)

答案 3 :(得分:0)

def col(row):
    for item in row.split()[1:]:
        yield int(item)

def row(fp):
    for row in fp:
        yield list(col(row))

with open("input.txt") as fp:
    result = list(row(fp))

print result