Reputation: 1699
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
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
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