How can I convert a list of strings to an array of float numbers?

Ahmad Tanha

I'm trying to convert a list of strings to an array of callable float numbers in Python, but I encounter an error. Here is a part of my code:

list=['1 2 3', '4 5 6']
for x in list:
   x=float(x)

ValueError: could not convert string to float: '1 2 3'
Cory Kramer

You can use a nested list comprehension for this. The first can iterate through your strings, then for each string you can str.split and convert each element to float from there.

>>> data = ['1 2 3', '4 5 6']
>>> [[float(i) for i in row.split()] for row in data]
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I convert an array of numbers to strings?

How can I convert the list string to a float

How to convert negative strings in float numbers in pandas?

ValueError: could not convert string to float---how to convert a list of lists of strings into a numpy array type float?

How do I convert strings in an array to numbers using forEach?

How can i convert Map of Strings and Object to a Map of Strings and List

How to convert a 2D array of strings and numbers to a numpy float array?

How to convert nested list of numbers to list of strings?

How to convert a list of numbers to a list of strings?

How can I convert an array of strings into an associative array in PHP?

how to convert an array of strings to array of numbers?

How can I convert a list to float inside a for statement

How can i turn an array of arrays from strings to numbers in Javascript?

convert strings in list to float

How do I convert integers in a list to float numbers when the elements contain both words and numbers?

How to convert an array of strings to float in Javascript

How do I convert an array of strings into append-able list?

Given two list of strings, how can I convert them into a into a dict?

How can I convert a list of strings into sympy variables?

How can I convert a list of character strings to unique single characters?

How can I convert a string of numbers to an array or vector of integers in Rust?

How can I convert an array to an object by splitting strings?

How can I convert an array of strings to an object using jq?

How can i convert comma separated query String to a Array of Strings

How to convert a string containing several float numbers into an array of float in Python?

How can I convert a list of numbers to list of sums of numbers up to current element in python, using a functional approach?

how to convert strings to float

How can I remove ".0" of float numbers?

how to create any array list of **numbers** and not strings?