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

如何在python中将文件读取到列表中?,python,file,Python,File,我有一个以空格分隔的文件 例如 我想把每一行放入一个列表中,从而创建一个列表列表。我想省略文件的第一列,并将类型转换为整数,以便对其执行整数操作。因此,about示例的列表应该类似于[[1,2]、[2,3]、[2,3]、[1,3]] 下面列出了我使用的代码 class Graph: def __init__(self): f = open("Ai.txt") next(f) self.coordinates = [] cou

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

我想把每一行放入一个列表中,从而创建一个列表列表。我想省略文件的第一列,并将类型转换为整数,以便对其执行整数操作。因此,about示例的列表应该类似于[[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
如果你需要整数,你可以用一些地图把它包起来

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

[[1, 2], [2, 3], [2, 3], [1, 3]]
我让你处理文件部分:p


希望这有帮助:)

忘记转换为int。。。还有,你真的需要那个内部的
列表吗?我不完全确定你是否可以不用它来解包。。。所以我下定决心使用它(在
列表中
)。。。我太懒了,不敢尝试。。。但我现在就要知道答案是不我不需要这个:P
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:]))
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]]
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