Jayasuriya Perera
Jayasuriya Perera

Reputation: 83

Array to list python

I need to convert numpy array in to a list

[ [1.        ] [0.89361702] [0.4893617 ] [0.44680851] [0.0212766 ] [0.        ] ]

this to

[ 1 ,0.89361702, 0.4893617,  0.44680851 ,0.0212766 ,0]

But when i use

duration= du.tolist()

duration looks like this

[[1.0],
[0.8936170212765937],
[0.4893617021276597],
[0.4468085106382951],
[0.02127659574468055],
[0.0]]

Please ignore the numbe of decimal points

Upvotes: 0

Views: 1974

Answers (4)

smerllo
smerllo

Reputation: 3375

very simple:

[ls[0] for ls in arr]

I Hope this helps

Upvotes: 1

Use du.reshape(-1).tolist(). reshape(-1) returns a view (whenever possible) of the flattened array, so it minimizes the overhead as compared to flatten that creates a copy.

Upvotes: 3

Alexandre B.
Alexandre B.

Reputation: 5500

Surprised nobody suggested the flatten method from numpy (doc). It's mostly the same as the ravel method suggested by @Gilles-Philippe Paillé.

One example:

import numpy as np

data = [[1.0],
        [0.89361702],
        [0.4893617],
        [0.44680851],
        [0.0212766],
        [0.0],]
array = np.array(data, dtype=float)

my_list= array.flatten().tolist()

print(my_list)
# [1.0, 0.89361702, 0.4893617, 0.44680851, 0.0212766, 0.0]

Upvotes: 2

Rudolf Fanchini
Rudolf Fanchini

Reputation: 99

I did it this way.

dura = [[1.0],
[0.8936170212765937],
[0.4893617021276597],
[0.4468085106382951],
[0.02127659574468055],
[0.0]]
new = []
for x in dura:
    if len(x)== 1:
        new.append(x[0])

and got this when printing new

[1.0, 0.8936170212765937, 0.4893617021276597, 0.4468085106382951, 0.02127659574468055, 0.0]

Upvotes: 0

Related Questions