Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert select items while unpacking a list in python

Tags:

python

I have a list of strings. I want to unpack it to individual variables, and while doing this I want to convert some of the strings to ints.

The brute force method might look like this

>>> my_list = ['a', '1', '2']
>>> a, b, c = my_list
>>> b = int(b)
>>> c = int(c)
>>> a,b,c
('a', 1, 2)

I'm looking for a way to do the conversions as part of the original assignment, so that I end up with something like:

>>> a, b, c = < some magic here >
>>> a,b,c
('a', 1, 2)

Anyone know what magic I'm looking for?

like image 937
user3067927 Avatar asked Jun 23 '26 23:06

user3067927


1 Answers

Fix your my_list either up stream or now before unpacking:

my_list = ['a', '1', '2']

a,b,c = (int(x) if x.isnumeric() else x for x in my_list )
print(type(a), type(b), type(c)) 
# <str, int int>
like image 159
MooingRawr Avatar answered Jun 25 '26 14:06

MooingRawr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!