[英]Creating a list of lists from an input file
I have an input file with multiple values per line, eg:我有一个每行有多个值的输入文件,例如:
1 3 5
2 6 1
8 9 2
I want to import these numbers to a list of lists, so that each line is a list within a list of lists:我想将这些数字导入列表列表,以便每一行都是列表列表中的一个列表:
data= [[1 3 5], [2 6 1], [8 9 2]]
etc. data= [[1 3 5], [2 6 1], [8 9 2]]
等等。
Is there an easy way of doing this?有没有简单的方法来做到这一点? I've looked at
readline
, readlines
, lines
, but am still not sure how to create this format.我看过
readline
, readlines
, lines
,但我仍然不确定如何创建这种格式。 Ultimately, I'd like to perform the same set of operations on each of the lists, so this format seems the most sensible.最终,我想对每个列表执行相同的操作集,因此这种格式似乎是最明智的。
我会做:
data = [map(int, line.split()) for line in fname if line.strip()]
If you data looks just the way you presented it, try something like:如果您的数据看起来就像您呈现的那样,请尝试以下操作:
data = []
with open('filename.txt', 'r') as f:
for line in f:
if not line.strip(): continue #skips blank lines
data.append(map(int, line.strip().split(" "))) #or .split()
Additionally, if you will be doing the same numerical operations on each of the rows, you may want to try numpy
.此外,如果您将对每一行进行相同的数值运算,您可能想尝试
numpy
。
In [1]: import numpy as np
In [2]: np.genfromtxt('filename.txt')
Out[2]:
array([[ 1., 3., 5.],
[ 2., 6., 1.],
[ 8., 9., 2.]])
In [3]: x = np.genfromtxt('filename.txt')
In [4]: x.mean(axis=1)
Out[4]: array([ 3., 3., 6.333333333333333])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.