簡體   English   中英

如何在python中將文件讀入列表?

[英]How do I read a file to a list in python?

我有一個由空格分隔的文件 例如。

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

我想將每一行放入一個列表中,從而創建一個列表列表。 我想省略文件的第一列,我想將類型轉換為整數,以便我可以對其執行整數運算。 因此,關於示例的列表應該類似於 [[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
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]]
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]]

PS:我讓你處理文件部分:P

希望這可以幫助 :)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM