[英]what is the most efficient way of concat two numbers to one number in python?
what is the most efficient way of concat two numbers to one number in python? 在python中将两个数字连接到一个数字的最有效方法是什么?
numbers are always in between 0 to 255, i have tested few ways by Concat as string and cast back to int but they are very costly in time vice for my code. 数字总是介于0到255之间,我已经通过Concat测试了几种方式作为字符串并转换回int但是它们对我的代码来说非常昂贵。
example 例
a = 152
c = 255
d = concat(a,c)
answer: 回答:
d = 152255
If the numbers are bounded, just multiply and add: 如果数字有界,只需乘以并加:
>>> a = 152
>>> c = 255
>>> d = a*1000+c
>>> d
152255
>>>
This is pretty fast: 这很快:
def concat(a, b):
return 10**int(log(b, 10)+1)*a+b
It uses the logarithm to find how many times the first number must be multiplied by 10 for the sum to work as a concatenation 它使用对数来查找第一个数字必须乘以10的次数,以使总和作为连接起作用
In [1]: from math import log
In [2]: a = 152
In [3]: b = 255
In [4]: def concat(a, b):
...: return 10**int(log(b, 10)+1)*a+b
...:
In [5]: concat(a, b)
Out[5]: 152255
In [6]: %timeit concat(a, b)
1000000 loops, best of 3: 1.18 us per loop
Yeah, there you go: 是的,你去了:
a = 152
b = 255
def concat(a, b):
n = next(x for x in range(10) if 10**x>a) # concatenates numbers up to 10**10
return a * 10**n + b
print(concat(a, b)) # -> 152255
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.