简体   繁体   中英

How to turn a tuple into an integer in Python (examples inside)?

I have a list of tuples:

"(1,2,3), (2,3,1)..."

I would like to change this into a list of integers:

"123, 231..."

How might I go about doing this? Thanks in advance.

A more functional approach:

[reduce(lambda a, x: a * 10 + x, t) for t in tuples]

edit:

Just for fun, a little benchmark against JBernardo's answer:

In [21]: %timeit [int(''.join(str(i) for i in t)) for t in tuples]
100000 loops, best of 3: 7.54 us per loop

In [22]: %timeit [reduce(lambda a, x: a * 10 + x, t) for t in tuples]
1000000 loops, best of 3: 1.55 us per loop

edit 2:

Akavall pointed out my original answer only works when the tuples have exclusively single digit integers.

If this is unacceptable for your use case, JBernardo's answer is probably a simpler way to do this. But just for fun:

[reduce(lambda a, x: a * 10**(len(str(x))) + x, t) for t in tuples]

or without any string conversions at all:

from math import log10
[reduce(lambda a, x: a * 10**(int(log10(x))+1) + x, t) for t in tuples]

怎么样:

[int(''.join(str(i) for i in t)) for t in tuples]

Less complex than @Luke's

[sum(x * 10**i for i, x in enumerate(t[1][::-1])) for t in tuples]

It just sum like x1 + x2 * 10^2 + ... + xN * 10^n

[::-1] - to reverse the tuple, enumerate to get (xN, N) pairs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM