在Python中将二进制列表(或数组)转换为整数的最快方法 [英] Fastest way to convert a binary list(or array) into an integer in Python

查看:913
本文介绍了在Python中将二进制列表(或数组)转换为整数的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个包含1和0的列表(或数组).

Suppose there is a list(or an array) which contains 1s and 0s.

gona = [1, 0, 0, 0, 1, 1]

我想将其转换为由二进制值100011(由列表中的元素组成的数字)表示的整数.

I want to convert this into the integer represented by the binary value 100011 (The number made out of the elements in the list).

我知道可以这样做.

int("".join(map(str, gona)),2)

int("".join([str(i) for i in gona]),2)

还有其他更快的方法吗?

Is there any other faster way to do this?

推荐答案

这是我想出的最快的方法.您的初始解决方案略有不同:

This is the fastest I came up with. A slight variation of your initial solution:

digits = ['0', '1']
int("".join([ digits[y] for y in x ]), 2)

%timeit int("".join([digits[y] for y in x]),2)
100000 loops, best of 3: 6.15 us per loop
%timeit int("".join(map(str, x)),2)
100000 loops, best of 3: 7.49 us per loop

(顺便说一句,在这种情况下,似乎使用列表理解比使用生成器表达式要快.)

(Btw, it seems that in this case, using a list comprehension is faster than using a generator expression.)

此外,我讨厌成为聪明人,但是您总是可以用内存换取速度:

Also, I hate being a smartass, but you can always trade memory for speed:

# one time precalculation
cache_N = 16  # or much bigger?!
cache = {
   tuple(x): int("".join([digits[y] for y in x]),2)
   for x in itertools.product((0,1), repeat=cache_N)
}

然后:

res = cache[tuple(x)]

行进速度更快.当然,这仅在某种程度上是可行的...

Way faster. Of course, this is only feasible up to a point...

我现在看到您说您的列表包含32个元素.在这种情况下,缓存解决方案可能是行不通的,但是我们有更多的方式来交换内存速度.例如,使用cache_N=16肯定可行,您可以访问它两次:

I now see you say your lists have 32 elements. In this case the caching solution is probably infeasible, BUT we have more ways to trade speed for memory. E.g., with cache_N=16, which is surely feasible, you can access it twice:

c = 2 ** cache_N # compute once
xx = tuple(x)
cache[xx[:16]] * c + cache[xx[16:]]

%timeit cache[xx[:16]] * c + cache[xx[16:]]
1000000 loops, best of 3: 1.23 us per loop  # YES!

这篇关于在Python中将二进制列表(或数组)转换为整数的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆