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?
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.
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.
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)]
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)))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With