简体   繁体   English

从python中ndarray中的所有元素获取n位置的位

[英]Get bit on n position from all elements in ndarray in python

i have a 3D array of int32 . 我有一个int32的3D数组。 I would like to transform each item from array to its corresponding bit value on "n" th position. 我想将每个项目从数组转换为第n个位置上的相应位值。 My current approach is to loop through the whole array, but I think it can be done much more efficiently. 我当前的方法是遍历整个数组,但是我认为可以更高效地完成。

for z in range(0,dim[2]):
 for y in range(0,dim[1]):
  for x in range(0,dim[0]):
   byte='{0:032b}'.format(array[z][y][x])
   array[z][y][x]=int(byte>>n) & 1

Looking forward to your answers. 期待您的回答。

Unless there is an intrinsic relation between the different points, you have no other choice than to loop over them to discover their current values. 除非不同点之间没有内在联系,否则您别无选择,只能遍历它们以发现其当前值。 So the best you can do, will always be O(n^3) 因此,您能做的最好的事情就是永远是O(n ^ 3)

What I don't get however, is why you go over the hassle of converting a number to a 32bit string, then back to int. 但是,我没有得到的是为什么您要麻烦将数字转换为32位字符串,然后再转换为int的麻烦。

If you want to check if the nth bit of a number is set, you would do the following: 如果要检查是否设置了数字的第n位,请执行以下操作:

power_n = 1 << (n - 1)
for z in xrange(0,dim[2]):
 for y in xrange(0,dim[1]):
  for x in xrange(0,dim[0]):
   array[z][y][x]= 0 if array[z][y][x] & power_n == 0 else 1

Not that in this example, I'm assuming that N is a 1-index (first bit is at n=1). 并非在此示例中,我假设N是1索引(第一位在n = 1)。

If you are dealing with large arrays, you are better off using numpy . 如果要处理大型数组,最好使用numpy Applying bitwise operations on a numpy array is much faster than applying it on python lists. 在numpy数组上应用按位运算比在python列表上应用按位运算要快得多。

import numpy as np
a = np.random.randint(1,65, (2,2,2))

print a
Out[12]: 
array([[[37, 46],
        [47, 34]],

       [[ 3, 15],
        [44, 57]]])
print (a>>1)&1
Out[16]: 
array([[[0, 1],
        [1, 1]],

       [[1, 1],
        [0, 0]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM