将整数列表转换为一个数字?

时间:2009-01-29 00:16:23

标签: python

我有一个整数列表,我想将其转换为一个数字,如:

numList = [1, 2, 3]
num = magic(numList)

print num, type(num)
>>> 123, <type 'int'>

实现 magic 功能的最佳方法是什么?

编辑
我确实找到this,但似乎必须有更好的方法。

18 个答案:

答案 0 :(得分:138)

# Over-explaining a bit:
def magic(numList):         # [1,2,3]
    s = map(str, numList)   # ['1','2','3']
    s = ''.join(s)          # '123'
    s = int(s)              # 123
    return s


# How I'd probably write it:
def magic(numList):
    s = ''.join(map(str, numList))
    return int(s)


# As a one-liner  
num = int(''.join(map(str,numList)))


# Functionally:
s = reduce(lambda x,y: x+str(y), numList, '')
num = int(s)


# Using some oft-forgotten built-ins:
s = filter(str.isdigit, repr(numList))
num = int(s)

答案 1 :(得分:42)

两种解决方案:

>>> nums = [1, 2, 3]
>>> magic = lambda nums: int(''.join(str(i) for i in nums)) # Generator exp.
>>> magic(nums)
123
>>> magic = lambda nums: sum(digit * 10 ** (len(nums) - 1 - i) # Summation
...     for i, digit in enumerate(nums))
>>> magic(nums)
123

面向map的解决方案实际上已经出现在我的方框中 - 你肯定不应该使用sum来解决那些可能很大的问题:

Timeit Comparison

import collections
import random
import timeit

import matplotlib.pyplot as pyplot

MICROSECONDS_PER_SECOND = 1E6
FUNS = []
def test_fun(fun):
    FUNS.append(fun)
    return fun

@test_fun
def with_map(nums):
    return int(''.join(map(str, nums)))

@test_fun
def with_interpolation(nums):
    return int(''.join('%d' % num for num in nums))

@test_fun
def with_genexp(nums):
    return int(''.join(str(num) for num in nums))

@test_fun
def with_sum(nums):
    return sum(digit * 10 ** (len(nums) - 1 - i)
        for i, digit in enumerate(nums))

@test_fun
def with_reduce(nums):
    return int(reduce(lambda x, y: x + str(y), nums, ''))

@test_fun
def with_builtins(nums):
    return int(filter(str.isdigit, repr(nums)))

@test_fun
def with_accumulator(nums):
    tot = 0
    for num in nums:
        tot *= 10
        tot += num
    return tot

def time_test(digit_count, test_count=10000):
    """
    :return: Map from func name to (normalized) microseconds per pass.
    """
    print 'Digit count:', digit_count
    nums = [random.randrange(1, 10) for i in xrange(digit_count)]
    stmt = 'to_int(%r)' % nums
    result_by_method = {}
    for fun in FUNS:
        setup = 'from %s import %s as to_int' % (__name__, fun.func_name)
        t = timeit.Timer(stmt, setup)
        per_pass = t.timeit(number=test_count) / test_count
        per_pass *= MICROSECONDS_PER_SECOND
        print '%20s: %.2f usec/pass' % (fun.func_name, per_pass)
        result_by_method[fun.func_name] = per_pass
    return result_by_method

if __name__ == '__main__':
    pass_times_by_method = collections.defaultdict(list)
    assert_results = [fun([1, 2, 3]) for fun in FUNS]
    assert all(result == 123 for result in assert_results)
    digit_counts = range(1, 100, 2)
    for digit_count in digit_counts:
        for method, result in time_test(digit_count).iteritems():
            pass_times_by_method[method].append(result)
    for method, pass_times in pass_times_by_method.iteritems():
        pyplot.plot(digit_counts, pass_times, label=method)
    pyplot.legend(loc='upper left')
    pyplot.xlabel('Number of Digits')
    pyplot.ylabel('Microseconds')
    pyplot.show()

答案 2 :(得分:8)

def magic(number):
    return int(''.join(str(i) for i in number))

答案 3 :(得分:6)

def magic(numbers):
    return int(''.join([ "%d"%x for x in numbers]))

答案 4 :(得分:5)

为了完整起见,这是一个使用print()的变体(适用于Python 2.6-3.x):

from __future__ import print_function
try: from cStringIO import StringIO
except ImportError:
     from io import StringIO

def to_int(nums, _s = StringIO()):
    print(*nums, sep='', end='', file=_s)
    s = _s.getvalue()
    _s.truncate(0)
    return int(s)

不同解决方案的时间表现

我测量了@cdleary's functions的效果。结果略有不同。

使用由<:p>生成的输入列表测试每个函数

def randrange1_10(digit_count): # same as @cdleary
    return [random.randrange(1, 10) for i in xrange(digit_count)]

您可以通过--sequence-creator=yourmodule.yourfunction命令行参数提供自己的功能(见下文)。

列表(len(nums) == digit_count)中给定数量的整数的最快函数是:

    1..30

  • len(nums)

    def _accumulator(nums):
        tot = 0
        for num in nums:
            tot *= 10
            tot += num
        return tot
    
  • 30..1000

  • len(nums)

    def _map(nums):
        return int(''.join(map(str, nums)))
    
    def _imap(nums):
        return int(''.join(imap(str, nums)))
    

Figure: N = 1000

|------------------------------+-------------------|
| Fitting polynom              | Function          |
|------------------------------+-------------------|
| 1.00  log2(N)   +  1.25e-015 | N                 |
| 2.00  log2(N)   +  5.31e-018 | N*N               |
| 1.19  log2(N)   +      1.116 | N*log2(N)         |
| 1.37  log2(N)   +      2.232 | N*log2(N)*log2(N) |
|------------------------------+-------------------|
| 1.21  log2(N)   +      0.063 | _interpolation    |
| 1.24  log2(N)   -      0.610 | _genexp           |
| 1.25  log2(N)   -      0.968 | _imap             |
| 1.30  log2(N)   -      1.917 | _map              |

Figure: N = 1000_000

要绘制第一个数字下载cdleary.py and make-figures.py并运行(numpymatplotlib必须安装到绘图中):

$ python cdleary.py 

$ python make-figures.py --sort-function=cdleary._map \
> --sort-function=cdleary._imap \
> --sort-function=cdleary._interpolation \
> --sort-function=cdleary._genexp --sort-function=cdleary._sum \
> --sort-function=cdleary._reduce --sort-function=cdleary._builtins \
> --sort-function=cdleary._accumulator \
> --sequence-creator=cdleary.randrange1_10 --maxn=1000 

答案 5 :(得分:3)

伪码:

int magic(list nums)
{
  int tot = 0

  while (!nums.isEmpty())
  {
    int digit = nums.takeFirst()
    tot *= 10
    tot += digit
  }

  return tot
}

答案 6 :(得分:3)

对我来说这看起来很干净。

def magic( aList, base=10 ):
    n= 0
    for d in aList:
        n = base*n + d
    return n

答案 7 :(得分:3)

只要列表中的每个元素只是一个数字,此方法就可以在2.x中运行。但你实际上不应该使用它。太可怕了。

>>> magic = lambda l:int(`l`[1::3])
>>> magic([3,1,3,3,7])
31337

答案 8 :(得分:3)

使用生成器表达式:

def magic(numbers):
    digits = ''.join(str(n) for n in numbers)
    return int(digits)

答案 9 :(得分:2)

单行,无需与str

进行投射
def magic(num):
    return sum(e * 10**i for i, e in enumerate(num[::-1]))

答案 10 :(得分:2)

如果列表仅包含整数:

reduce(lambda x,y: x*10+y, list)

答案 11 :(得分:1)

我发现一些例子与python 3不兼容我从@Triptych

测试一个

s = filter(str.isdigit, repr(numList)) num = int(s)

在python 3中它会给出错误

TypeError: int() argument must be a string, a bytes-like object or a number, not 'filter'

我认为更简单和兼容的方式是

def magic(num_list):
    return int("".join(map(str, num_list)))

答案 12 :(得分:1)

这可能会有所帮助

def digits_to_number(digits):
    return reduce(lambda x,y : x+y, map(str,digits))

print digits_to_number([1,2,3,4,5])

答案 13 :(得分:0)

如果你碰巧使用numpy(import numpy as np):

In [24]: x
Out[24]: array([1, 2, 3, 4, 5])

In [25]: np.dot(x, 10**np.arange(len(x)-1, -1, -1))
Out[25]: 12345

答案 14 :(得分:0)

我在尝试将列表转换为基于C样式指针的基础int的实际值时发现了该线程,但是在这种情况下,其他答案似乎都不起作用。我认为以下解决方案可以按预期工作,即使不一定能回答原始问题,也可能对其他人有用。

def listToInt(x, reverseBytes=False):
  if reverseBytes:
    x = x[::-1]
  return reduce(lambda x,y: x*256+y, x)

listToInt([1, 249]) == 505

listToInt([249, 1], True) == 505

此方法的主要价值是模拟将字节数组转换为其他数据类型的行为,例如uint16,无论是大端还是小端系统,Python似乎都无法原生完成。

答案 15 :(得分:0)

对于聚会来说来不及了,这是不转换为字符串的方法

select * from [Table] where Id in (@FromId) 
if @@ROWCOUNT =0
select * from  [Table] where TypeId =@TypeId

答案 16 :(得分:0)

我认为这似乎是最简单的解决方案不需要任何 fcn

res = int(''.join(numList))

注意:此实现在 Python 3 中

答案 17 :(得分:0)

希望这个单行公式也有用:

s=sum([numlist[i] * 10**(len(numlist)-i-1) for i in range(len(numlist))]) 
相关问题