Converting list to float array

Asked

Viewed 237 times

-1

I am working on an import of data, which are in format, as in the example:

[-2.814285863362681, -2.814158589901394, -2.8123844084634873]
[-2.874285863362681, -2.054158589901394, -2.6523844084634873]

.
.
.

I used this code to import, already removing the ' n' with the strip()

with open(coeffs_csv) as inp:
        signals_coeffs_cluster = inp.readlines()
        signals_coeffs_cluster = [x.strip() for x in signals_coeffs_cluster]

But I need these data in float and array format, so I worked on the code for only the second line:

signal_1.append(signals_coeffs_cluster[1])

signal_1 = [k.replace('[', '').replace(']', '') for k in signal_1]

And this returns me a size 1, IE, it is all concatenated inside signal_1, I can not, for example make signal_1[2], because there is no position.

How to proceed to extract a line from the input file and separate them into individual float array form ?

array_1 = [-2.814285863362681, -2.814158589901394, -2.8123844084634873] 
array_2 = [-2.874285863362681, -2.054158589901394, -2.6523844084634873]

And so on and so forth ?

EDIT:

Use this code to export:

coeffs = cA3.tolist()

    with open(coeffs_csv, "a") as output:
        json.dump(coeffs, output)
        output.write('\n')

Thank you

  • Something tells me this is a JSON file. Now try: import json;with open(coeffs_csv) as f:;data = json.load(f); ... Attention, remove points and commas in the code, I just put them so you know where to change lines

  • I tested this solution, but it gives an extradata error, I believe it is due to the fact that I add one more line to each execution of the code when I export this data to a file

1 answer

0


You can use eval to turn a string into its Python equivalent:

minha_lista_str = '[1, 2, "a", 2.3]'
minha_lista = eval(minha_lista_str)
print(minha_lista, type(minha_lista))
# [1, 2, 'a', 2.3] <class 'list'>

Then your code stays:

with open(coeffs_csv) as inp:
        signals_coeffs_cluster = [eval(x) for x in inp.readlines()]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.