简体   繁体   中英

Python: How to convert multiple list that have multiple digits into array?

I have a text file with listed 4 x 3 binary values as such:

1 0 1
0 0 1
1 1 0
0 0 1

When I read this file in python, it is in this form:

import numpy as np
with open("test.txt")as g:
    p=g.read().splitlines()
    q=[];
    for m in p:
        q.append(int(m));
    p=q;

Python window:

>>> p
['1 0 1', '0 0 1', '1 1 0', '0 0 1']

How to convert it into array:

array([[ 1.0,  0.0,  1.0],
   [ 0.0,  0.0,  1.0],
   [ 1.0,  1.0,  0.0],
   [ 0.0,  0.0,  1.0]])

The simplest solution by far is to skip all the intermediate steps of reading the file of your own and converting the lines to lists of lists and just use numpy.loadtxt() . The values will be of float type by default, so you won't have to do anything more.

import numpy as np

dat = np.loadtxt('test.txt')

You can loop over each line of p , split the string into separate numbers and, finally, convert each substring into a float :

import numpy as np

p = ['1 0 1', '0 0 1', '1 1 0', '0 0 1']
print np.array([map(float, line.split()) for line in p])

Output:

[[ 1.  0.  1.]
 [ 0.  0.  1.]
 [ 1.  1.  0.]
 [ 0.  0.  1.]]

Assuming you're guaranteed a sane enough input you can split the strings and convert the fragments to int :

def str2ints(l):
    return [int(frag) for frag in l.split()]

This function takes one line and splits it into parts, fx "1 0 1" are split into ["1", "0", "1"] then I use list comprehension and converts the fragments to an int.

You use more of list comprehension to do it on the entire p :

[str2ints(l) for l in p]

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