简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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