![](/img/trans.png)
[英]Inputting a file of mixed data types and converting numbers into ints using Python
[英]Inputting data from a text file with multiple numbers on each line - Python
可以說我有一個數據文件,里面有這個文件:
23 33 45
91 81 414
28 0 4
7 9 14
8 9 17
1 1 3
38 19 84
如何將其導入到列表中,以便每個人單獨為其編號?
您可以使用numpy loadtxt將數據文件讀取到numpy數組
from numpy import loadtxt
a,b,c = loadtxt("filename", usecols=(0,1,2), unpack=True)
輸出量
a = array([23, 91, 28, 7, 8, 1, 38])
您也可以使用python內置函數(如打開文件,拆分和讀取行)
with open('file.txt') as f:
for line in f:
a, b, c = map(int, line.split())
另一種方法是
file = open(filename)
file_data = file.readlines()
但是,輸出將是字符串列表。 也就是說,列表中的每個元素將代表文件中的一行。 如果使用上面的代碼,輸出將如下所示
file_data = ['23 33 45', '91 81 414', '28 0 4 ', '7 9 14', '8 9 17', '1 1 3', '38 19 84']
您可能希望它們轉換為float或int。 您可以再次使用numpy的fromstring模塊來做到這一點
from numpy import fromstring
data = [fromstring(i, dtype=float, sep=' ') for i in file_data ]
注意,我在上面的代碼中使用了列表推導(比常規的python for循環要快。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.