Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy and beautiful way to cast the items in a list to different types?

Tags:

python

I got a list of strings from an REST API. I know from the documentation that the item at index 0 and 2 are integers and item at 1 and 3 are floats.

To do any sort of computation with the data I need to cast it to the proper type. While it's possible to cast the values each time they're used I rather prefer to cast the list to correct type before starting the computations to keep the equations cleaner. The code below is working but is very ugly:

rest_response = ['23', '1.45', '1', '1.54']
first_int = int(rest_response[0])
first_float = float(rest_response[1])
second_int = int(rest_response[2])
second_float = float(rest_response[3])

As I'm working with integers and floats in this particular example one possible solution is to cast each item to float. float_response = map(float, rest_response). Then I can simply unpack the list to name the values accordingly in the equations.

first_int, first_float, second_int, second_float = float_response

That is my current solution (but with better names) but while figuring that one out I became curious if there's any good pythonic solution to this kind of problem?

like image 930
Markus Avatar asked Aug 16 '17 13:08

Markus


People also ask

How do you write a cast list in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do you convert a list to a float in Python?

The most Pythonic way to convert a list of strings to a list of floats is to use the list comprehension floats = [float(x) for x in strings] . It iterates over all elements in the list and converts each list element x to a float value using the float(x) built-in function.


2 Answers

Define a second list that matches your type casts, zip it with your list of values.

rest_response = ['23', '1.45', '1', '1,54']
casts = [int, float, int, float]
results = [cast(val) for cast, val in zip(casts, rest_response)]
like image 180
Billy Avatar answered Oct 20 '22 01:10

Billy


this is a solution using itertools.cycle in order to cycle through the cast functions:

from itertools import cycle

first_int, first_float, second_int, second_float = [cast(f)
    for f, cast in zip(rest_response, cycle((int, float)))]
like image 20
hiro protagonist Avatar answered Oct 19 '22 23:10

hiro protagonist