Data Type Conversion for Nested Lists in Python

Asked 2 years ago, Updated 2 years ago, 32 views

I use Python 3.6.Now, I would like to convert the list of strings like the following into a number (float) with the structure of the list intact.

·The current list (string)

str_list=[[["1.2", "3.4", "5.6", "7.8"]]

·List I want

 float_list=[1.2, 3.4], [5.6, 7.8]]

I'm looking for a way to handle this easily when it's multidimensional.

For example, if you use for, you will see the following:

str_list=[[["1.2", "3.4", "5.6", "7.8"]]
float_list = [ ]

for i in range (len(str_list)) :
    float_list.append ([float(str_lis[i][j]) for jin range(len(str_list[i]))]))

for inclusion only
 [[float(str_list[i][j]) for jin range(len(str_list[i]))] for i in range(str_list)]

If you write (in this case), you will get the list you want.
However, as the dimension goes up, I don't think I can write one by one.

So I'm looking for a function that can access (convert) all the elements in the list and keep the list structure intact. Is there such a function or method?

Please let me know if anyone knows.Thank you for your cooperation.

python python3

2022-09-30 14:31

1 Answers

How do you like this?

def functor(f,l):
  if isinstance(l,list):
    return [ functor(f,i)for i in ]
  else:
    return f(l)

str_list = [[[["1.2", "3.4"]], ["5.6", "7.8", "9.9" ]
float_list = functor(float, str_list)#[[[1.2, 3.4]], [5.6, 7.8], 9.9]


2022-09-30 14:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.