简体   繁体   English

从每行具有多个数字的文本文件输入数据-Python

[英]Inputting data from a text file with multiple numbers on each line - Python

Lets say I have a data file that has this inside it: 可以说我有一个数据文件,里面有这个文件:

23 33 45
91 81 414
28 0 4 
7 9 14
8 9 17
1 1 3
38 19 84

How can I import it into a list so that each individual number it its own item? 如何将其导入到列表中,以便每个人单独为其编号?

You can use, numpy loadtxt to read the data file to a numpy array 您可以使用numpy loadtxt将数据文件读取到numpy数组

  from numpy import loadtxt
  a,b,c = loadtxt("filename", usecols=(0,1,2), unpack=True)

Output 输出量

  a = array([23, 91, 28, 7, 8, 1, 38])

You could alternatively use the python builtin functions like open file, split and readlines 您也可以使用python内置函数(如打开文件,拆分和读取行)

with open('file.txt') as f:
for line in f:
  a, b, c = map(int, line.split())

Another approach is 另一种方法是

 file                = open(filename)
 file_data           = file.readlines()

But, the output will be a list of strings. 但是,输出将是字符串列表。 That is the each element in the list will represent one line in the file. 也就是说,列表中的每个元素将代表文件中的一行。 If you use the above code the output will look like 如果使用上面的代码,输出将如下所示

 file_data = ['23 33 45', '91 81 414', '28 0 4 ', '7 9 14', '8 9 17', '1 1 3', '38 19 84']

You might want them to convert to either float or int. 您可能希望它们转换为float或int。 you could do that using again numpy's fromstring module 您可以再次使用numpy的fromstring模块来做到这一点

  from numpy import fromstring
  data = [fromstring(i, dtype=float, sep=' ') for i in file_data ]

Notice that, I have used a list comprehension in the above code(which is faster than the conventional python for loop.) 注意,我在上面的代码中使用了列表推导(比常规的python for循环要快。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM