简体   繁体   English

在python中将两个数字连接到一个数字的最有效方法是什么?

[英]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.

相关问题 在 Python 中找到一个数的所有因子的最有效方法是什么? - What is the most efficient way of finding all the factors of a number in Python? Python Pandas:在循环中比较两个列表的最有效方法是什么? - Python Pandas: What is the most efficient way to compare two lists in a loop? 找到两个数字之和的最有效方法 - most efficient way to find a sum of two numbers 在 Python 中查找多个子字符串之一的最有效方法是什么? - What's the most efficient way to find one of several substrings in Python? 将一项写入 Python 中的 a.csv 文件的最有效方法是什么? - What is the most efficient way to write one item to a .csv file in Python? 在python中检查一组数字中数字存在的最高效方法是什么 - What is the most performant way to check existance of a number in a set of numbers in python 比较两组的最有效方法是什么? - What is the most efficient way of comparing two sets? 求两个数的平方和的平方根的最有效方法是什么? - What is the most efficient way of doing square root of sum of square of two numbers? 比较Python中2个字符串的最有效方法是什么 - What is the most efficient way of comparring 2 strings in Python Python - 生成填充的最有效方法是什么? - Python - What is the most efficient way to generate padding?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM