简体   繁体   中英

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

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'

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]]

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