簡體   English   中英

如何在python中將文本文件讀取為列表列表

[英]How do I read a text file as a list of lists in python

我有一個像這樣分成不同行的大文本文件:

35 4 23 12 8 \\n 23 6 78 3 5 \\n 27 4 9 10 \\n 73 5 \\n

我需要將其轉換為列表列表,每一行都是一個單獨的元素,如下所示:

[[35, 4, 23, 12, 8], [23, 6, 78, 3, 5], [27, 4, 9, 10], [73, 5], ....]

這可能就是你要找的...

with open('file_to_read.csv', 'rU') as f:
        l1 = []
        for ele in f:
            line = ele.split('\n')
            l1.append(line)
print(l1)

您可能只能使用numpygenfromtxt方法來執行此操作。

from numpy import genfromtxt 
lol = genfromtxt('myFile.csv', delimiter=' ')

在此處查找更多信息。

lines = [line.split() for line in open('yourtextfile.txt')]  # opens the text file and calls .split() on every line, effectively splitting on every space, creating a list of numbers.

或者,以下內容也會將您的值轉換為 int:

lines = [[int(v) for v in line.split()] for line in open('yourtextfile.txt')] # opens the text file and calls .split() on every line, effectively splitting on every space, creating a list of numbers that are converted to int()

暫無
暫無

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

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