Python将元组转换为整数

时间:2012-04-08 12:09:14

标签: python integer tuples

是否有任何函数可以将元组转换为整数?

示例:

input = (1, 3, 7)

output = 137

8 个答案:

答案 0 :(得分:25)

>>> reduce(lambda rst, d: rst * 10 + d, (1, 2, 3))
123

答案 1 :(得分:14)

>>> x = (1,3,7)
>>> int(''.join(map(str,x)))
137

答案 2 :(得分:4)

将它转换为字符串然后转换为int工作时,这是一种有点hackish的方法。我们拥有制作数字所需的所有信息,即:

  • 数字。
  • 数字的位置。

由于我们有这些信息,我们可以通过计算每个位置的每个单位的值来计算数字,然后将其乘以所述位置的数字。然后我们将结果加在一起,我们有我们的号码。这可以在一行中完成,如下所示:

test = (1, 2, 3)
sum((10**pos)*val for pos, val in enumerate(reversed(test)))

让我们打破这个:

>>> list(enumerate(reversed(test)))
[(0, 3), (1, 2), (2, 1)]

那么,如果我们将它倍增:

>>> list((10**pos)*val for pos, val in enumerate(reversed(test)))
[3, 20, 100]

所以我们总结得到123。

编辑:关于速度的说明:

python -m timeit "int(''.join(map(str,(1,2,3))))"
100000 loops, best of 3: 2.7 usec per loop

python -m timeit 'sum((10**pos)*val for pos, val in enumerate(reversed((1,2,3))))'
100000 loops, best of 3: 2.29 usec per loop

python -m timeit -s 'from functools import reduce' 'reduce(lambda rst, d: rst * 10 + d, (1, 2, 3))'
1000000 loops, best of 3: 0.598 usec per loop

所以,如果你的速度很快,Andrey Yazu's answer就有它。我觉得我觉得更具可读性。我总是发现lambdas丑陋,但总的来说,我认为它仍然是更易读的方法。

编辑2:使用非常大的元组:

长度20:

python -m timeit -s "x=tuple(list(range(1,10))*2)" "int(''.join(map(str, x)))"
100000 loops, best of 3: 5.45 usec per loop

python -m timeit -s "x=tuple(list(range(1,10))*2)" "sum((10**pos)*val for pos, val in enumerate(reversed(x)))" 
100000 loops, best of 3: 11.7 usec per loop

python -m timeit -s "x=tuple(list(range(1,10))*2)" -s 'from functools import reduce' 'reduce(lambda rst, d: rst * 10 + d, x)'
100000 loops, best of 3: 4.18 usec per loop

长度100:

python -m timeit -s "x=tuple(list(range(1,10))*10)" "int(''.join(map(str, x)))"
100000 loops, best of 3: 18.6 usec per loop

python -m timeit -s "x=tuple(list(range(1,10))*10)" "sum((10**pos)*val for pos, val in enumerate(reversed(x)))"
10000 loops, best of 3: 72.9 usec per loop

python -m timeit -s "x=tuple(list(range(1,10))*10)" -s 'from functools import reduce' 'reduce(lambda rst, d: rst * 10 + d, x)'
10000 loops, best of 3: 25.6 usec per loop

在这里我们看到最快的方法实际上是字符串操作 - 但是,实际情况是你不可能在10位数字的范围之外使用它 - 其中reduce()方法仍占主导地位速度明智的。我还会争辩说,字符串方法对于读者而言是黑客且不太清楚,通常优先于速度。

答案 3 :(得分:1)

这不会将整数转换为字符串并将它们连接起来:

>>> sum([(10 ** i) * input[len(input)-i-1] for i in range(len(input))])
123

这是一行中的for循环。

答案 4 :(得分:1)

怎么样:

In [19]: filter(set('0123456789').__contains__,str((1,2,3)))
Out[19]: '123'

我相信这是最简单的解决方案。

一个非常快速的解决方案是:

plus=ord("0").__add__ # separate out for readability; bound functions are partially-applied functions
int(str(bytearray(map(plus,x)))) #str is necessary

如何与下一个最快的解决方案相媲美:

$ python -m timeit -s 'x=tuple(list(range(1,10))*10)' 'plus=ord("0").__add__;int(str(bytearray(map(plus,x))))'
10000 loops, best of 3: 47.7 usec per loop

$ python -m timeit -s "x=tuple(list(range(1,10))*10)" "int(''.join(map(str, x)))"
10000 loops, best of 3: 59 usec per loop

答案 5 :(得分:1)

@Marcin bytearray解决方案确实是Python 2中最快的解决方案。

在Python 3中使用相同的行可以做到:

>>> plus = ord("0").__add__
>>> int(bytes(map(plus, x)))

Python 3以与Python 2不同的方式处理字符串和字节,因此为了更好地理解这种情况,我做了一些时间安排。以下是我在机器上得到的结果。

使用Python 2.7(code):

int(str(bytearray(map(plus, x))))           8.40 usec/pass
int(bytearray(map(plus, x)).decode())       9.85 usec/pass
int(''.join(map(str, x)))                   11.97 usec/pass
reduce(lambda rst, d: rst * 10 + d, x)      22.34 usec/pass

使用Python 3.2(code):

int(bytes(map(plus, x)))                    7.10 usec/pass
int(bytes(map(plus, x)).decode())           7.80 usec/pass
int(bytearray(map(plus,x)).decode())        7.99 usec/pass
int(''.join(map(str, x)))                   17.46 usec/pass
reduce(lambda rst, d: rst * 10 + d, x)      19.03 usec/pass

自己判断:)

答案 6 :(得分:1)

将元组更改为数字的最简单方法是使用字符串格式化。

input = (1, 3, 7)
output = int('{}{}{}'.format(input[0], input[1], input[2]))

# TEST
print(output) # 137
print(type(output)) # <class 'int'>

答案 7 :(得分:0)

另一种方法

>>> sum(n*10**i for (i,n) in enumerate(input[::-1]))
137

还有另一个

>>> int(str(input).translate(None,'(,) '))
137