1

我有以下格式的文本文件:

a,b,c,d,
1,1,2,3,
4,5,6,7,
1,2,5,7,
6,9,8,5,

如何有效地将其读入列表以获得以下输出?

list=[[1,4,1,6],[1,5,2,9],[2,6,5,8],[3,7,7,5]]
4

3 回答 3

3

假设文件名为spam.txt

$ cat spam.txt
a,b,c,d,
1,1,2,3,
4,5,6,7,
1,2,5,7,
6,9,8,5,    

使用列表推导zip()内置函数,您可以编写如下程序:

>>> with open('spam.txt', 'r') as file:
...     file.readline() # skip the first line
...     rows = [[int(x) for x in line.split(',')[:-1]] for line in file]
...     cols = [list(col) for col in zip(*rows)]
... 
'a,b,c,d,\n'
>>> rows
[[1, 1, 2, 3], [4, 5, 6, 7], [1, 2, 5, 7], [6, 9, 8, 5]]
>>> cols
[[1, 4, 1, 6], [1, 5, 2, 9], [2, 6, 5, 8], [3, 7, 7, 5]]

此外,zip(*rows)基于解包参数列表,它解包列表或元组,以便其元素可以作为单独的位置参数传递给函数。换句话说,zip(*rows)被简化为zip([1, 1, 2, 3], [4, 5, 6, 7], [1, 2, 5, 7], [6, 9, 8, 5])

编辑:

这是一个基于 NumPy 的版本供参考:

>>> import numpy as np
>>> with open('spam.txt', 'r') as file:
...     ncols = len(file.readline().split(',')) - 1
...     data = np.fromiter((int(v) for line in file for v in line.split(',')[:-1]), int, count=-1)
...     cols = data.reshape(data.size / ncols, ncols).transpose()
...
>>> cols
array([[1, 4, 1, 6],
       [1, 5, 2, 9],
       [2, 6, 5, 8],
       [3, 7, 7, 5]])
于 2012-08-07T05:19:03.283 回答
0

您可以尝试以下代码:

from numpy import*

x0 = []
for line in file('yourfile.txt'):
    line = line.split()
    x = line[1]
   x0.append(x)

for i in range(len(x0)):
print x0[i]

这里第一列附加到 x0[] 上。您可以以类似的方式附加其他列。

于 2012-08-07T05:16:12.417 回答
0

您可以使用 data_py 包从文件中读取列数据。使用安装此软件包

pip install data-py==0.0.1

例子

from data_py import datafile
df1=datafile("C:/Folder/SubFolder/data-file-name.txt")
df1.separator=","
[Col1,Col2,Col3,Col4,Col5]=["","","","",""]
[Col1,Col2,Col3,Col4,Col5]=df1.read([Col1,Col2,Col3,Col4,Col5],lineNumber)
print(Col1,Col2,Col3,Col4,Col5)

详情请点击链接https://www.respt.in/p/python-package-datapy.html

于 2020-08-03T14:28:25.583 回答