简体   繁体   中英

how do you convert a matrix to a array/list of strings?

How do you convert a matrix to a array/list of strings? input:

from numpy import array
M =   array([[1,1,2,5],
             [1,1,2,3],
             [1,2,0,4],
             [1,2,0,6],
             [1,2,0,8],
             [2,1,3,5],
             [2,2,9,6],
             [2,2,9,4]])

output:

N =   array(["1,1,2,5",
             "1,1,2,3",
             "1,2,0,4",
             "1,2,0,6",
             "1,2,0,8",
             "2,1,3,5",
             "2,2,9,6",
             "2,2,9,4"])

We have tried something like this:

list1=[]
for i in range(len(M)):
    list1=list1.append(str(M[i,0]),str(M[i,1]),str(M[i,2]),str(M[i,3]))

do that in a list comprehension, joining the converted integers to string with commas using str.join :

from numpy import array

M =   array([[1,1,2,5],
             [1,1,2,3],
             [1,2,0,4],
             [1,2,0,6],
             [1,2,0,8],
             [2,1,3,5],
             [2,2,9,6],
             [2,2,9,4]])

N = [",".join([str(x) for x in m]) for m in M]

print(N)

result:

['1,1,2,5', '1,1,2,3', '1,2,0,4', '1,2,0,6', '1,2,0,8', '2,1,3,5', '2,2,9,6', '2,2,9,4']

note: to get a numpy array just convert this list using array(N)

只需这样:

flat = [",".join([str(e) for e in row]) for row in M]

Suppose your list is a numpy array, you can use np.apply_along_axis() with a lambda function like this example:

M = array([[1, 1, 2, 5],
       [1, 1, 2, 3],
       [1, 2, 0, 4],
       [1, 2, 0, 6],
       [1, 2, 0, 8],
       [2, 1, 3, 5],
       [2, 2, 9, 6],
       [2, 2, 9, 4]])

N = np.apply_along_axis(lambda x: ','.join(map(str, x)), 1, M)

Output:

>>> N
array(['1,1,2,5', '1,1,2,3', '1,2,0,4', '1,2,0,6', '1,2,0,8', '2,1,3,5',
       '2,2,9,6', '2,2,9,4'], 
      dtype='<U7')

Suppose you got native list object, which would be no different from np.array :

In [1]: M = [[1,1,2,5], [1,1,2,3], [1,2,0,4], [1,2,0,6], [1,2,0,8], [2,1,3,5], [
   ...: 2,2,9,6],[2,2,9,4]]

In [2]: map(lambda x: ','.join(map(str, x)), M)
Out[2]: <map at 0x1049fca58>

In [3]: list(_)
Out[3]:
['1,1,2,5',
 '1,1,2,3',
 '1,2,0,4',
 '1,2,0,6',
 '1,2,0,8',
 '2,1,3,5',
 '2,2,9,6',
 '2,2,9,4']

What this does is convert every integer of each element in str object and join it with ',' .

You can try this:

l = [[1,1,2,5],
     [1,1,2,3],
     [1,2,0,4],
     [1,2,0,6],
     [1,2,0,8],
     [2,1,3,5],
     [2,2,9,6],
     [2,2,9,4]]

new = [','.join(map(str, i)) for i in l]

Output:

['1,1,2,5', '1,1,2,3', '1,2,0,4', '1,2,0,6', '1,2,0,8', '2,1,3,5', '2,2,9,6', '2,2,9,4']

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