Binary numpy array to list of integers?

前端 未结 5 1358
挽巷
挽巷 2020-11-27 07:08

I have a binary array, and I would like to convert it into a list of integers, where each int is a row of the array.

For example:

from numpy import *         


        
5条回答
  •  -上瘾入骨i
    2020-11-27 07:45

    @SteveTjoa's answer is fine, but for kicks, here's a numpy one-liner:

    In [19]: a
    Out[19]: 
    array([[1, 1, 0, 0],
           [0, 1, 0, 0],
           [0, 1, 1, 1],
           [1, 1, 1, 1]])
    
    In [20]: a.dot(1 << arange(a.shape[-1] - 1, -1, -1))
    Out[20]: array([12,  4,  7, 15])
    

    (arange is numpy.arange.)

    If the bits are in the opposite order, change the order of the values produced by arange:

    In [25]: a.dot(1 << arange(a.shape[-1]))
    Out[25]: array([ 3,  2, 14, 15])
    

提交回复
热议问题