Sibi
Sibi

Reputation: 48766

Converting list of tuples in functional way

I have the following list in Python:

[('1','2','3'),('5','6','7')]

I need to convert the tuples inside the list into integer([(1,2,3),(5,6,7)]) in a functional way.

I can do them for a list using this simple code: map(lambda x:int(x),['1','2','3'])

But how shall i apply the same concept for list of tuples ?

(I know the imperative way of doing this.)

Upvotes: 1

Views: 226

Answers (3)

user648852
user648852

Reputation:

This hybrid works:

>>> [tuple(map(int,t)) for t in [('1','2','3'),('5','6','7')]]
[(1, 2, 3), (5, 6, 7)]

Upvotes: 0

arikb
arikb

Reputation: 136

How about the following:

[tuple([int(str_int) for str_int in tup]) for tup in list_of_string_tuples]

Upvotes: 0

Amadan
Amadan

Reputation: 198526

tl = [('1','2','3'),('5','6','7')]
[tuple(int(x) for x in t) for t in tl]
# [(1, 2, 3), (5, 6, 7)]

If you really want the map syntax,

map(lambda t:tuple(map(int, t)), tl)
# [(1, 2, 3), (5, 6, 7)]

Upvotes: 6

Related Questions