簡體   English   中英

按列讀取文本文件並存儲在 python 列表中

[英]reading a text file columnwise and storing in a list in python

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

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]]

假設該文件名為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]])

您可以嘗試以下代碼:

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[]。 您可以以類似的方式附加其他列。

您可以使用 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

暫無
暫無

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

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