Python函数在二进制数组中查找1的索引和 [英] Python function to find indexes of 1s in binary array and
本文介绍了Python函数在二进制数组中查找1的索引和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的数组
I have an array which looks like this
[1, 0, 1 , 0 , 0, 1]
我想获取那些包含 1 的索引.所以在这里我会得到一个 [0, 2 , 5]
的数组然后基于它,我将创建一个新数组,该数组采用这些数字并用它们对 2 进行指数运算所以最后的数组是
And I want to get those indexes that have 1 in it.
So here I would get an array of [0, 2 , 5]
and then based on it I would create a new array that takes these numbers and exponantiate 2 with them
So the end array is
[2**0, 2**2, 2**5]
有没有办法尽快写出来?
Is there a way to write it as shortly as possible?
推荐答案
您可以在列表推导式中使用枚举:
you could use enumerate in a list comprehension:
a = [1, 0, 1 , 0 , 0, 1]
b = [2**idx for idx, v in enumerate(a) if v]
b
输出:
[1, 4, 32]
这篇关于Python函数在二进制数组中查找1的索引和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文