Python - working with specific tuple elements when doing multiple assignments?

Doing something like this

s = "12:00 PM"
hours, s = s.split(':')
hours = int(hours)

is there an elegant single-line idiom to do type conversion in the first element of a tuple before assignment?

Here is one option, but it's pretty messy

hours, s = (int(w) if w.isdigit() else w for w in s.split(':'))
+4
source share
5 answers

You can return the tuple from the built-in lambda function and call it:

hours, rest = (lambda t: (int(t[0]),t[1]))(s.split(':'))
+1
source

You can do:

>>> s = "12:00 PM"
>>> hour, the_rest=[(int(x),y) for x,y in [s.split(':')]][0]
>>> hour
12

If it does not offend to find the same character twice, you can also do:

>>> hour, the_rest=int(s[0:s.find(':')]), s[s.find(':')+1:]
+1
source

. :

hours = int(s.split(":", 1)[0])

: .split() , .

, :

hours = int(s[:s.index(":")])

, :

t = a, *b = t[int(a)] = "0:rest".split(":")
+1

date time.strptime

>>> from datetime import datetime
>>> datetime.strptime('12:00 PM', '%H:%M %p').hour
12
0

You can try to make some nifty features for this. Here is an example:

from itertools import zip_longest

def cast(*items):
    """
    Usage:
        cast('some', '123')(str, int) -> ['some', 123]
    """
    def to_type(*types):
        return [t(i) if t is not None else i 
                for i, t in zip_longest(items, types)]
    return to_type


s = "12:00 PM"
hours, _ = cast(*s.split(':'))(int)

print(hours, type(hours))  # 12 <class 'int'>
-1
source

All Articles