Raksha
Raksha

Reputation: 1699

Is there a way to force type onto a value from a list of types?

I'm pulling types from elsewhere and I'd like to apply those types to variables. So given a list, for example [<class 'str'>, <class 'int'>, <class 'float'>], is there a way to systematically apply them without setting up a bunch of if statements?

types = []
for t in ['abc', 1234, 1.2345]:
   types.append(type(t))
print(types)

vars = ['12.34', '56.78', '91.01']
for i in range(len(types)):
   print(<apply types[i] to vars[i]>)

output:

[<class 'str'>, <class 'int'>, <class 'float'>]
'12.34'
56
91.01 

Upvotes: 1

Views: 2856

Answers (2)

Barmar
Barmar

Reputation: 782107

A class object is callable, so you can do:

var = "123"
types = [str, int, float]
result = [typ(var) for typ in types]
print(result) # prints ['123', 123, 123.0]

Upvotes: 3

chepner
chepner

Reputation: 532043

zip and a list comprehension should do it

>>> types = [str, int, float]
>>> values = ["foo", "3", "3.14"]
>>> [t(x) for t, x in zip(types, values)]
["foo", 3, 3.14]

Upvotes: 0

Related Questions