二进制数组numpy的列出整数? [英] Binary numpy array to list of integers?

查看:281
本文介绍了二进制数组numpy的列出整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制数组,我想将它转换成整数列表,其中每个int是阵列中的一行。

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.

例如:

from numpy import *
a = array([[1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 1, 1, 1]])

我想转换 A [12,4,7,15]

推荐答案

我曾问过类似的问题<一href=\"http://stackoverflow.com/questions/4065737/python-numpy-convert-list-of-bools-to-unsigned-int\">here.这里是我的回答,适合你的问题:

I once asked a similar question here. Here was my answer, adapted for your question:

def bool2int(x):
    y = 0
    for i,j in enumerate(x):
        y += j<<i
    return y

In [20]: a
Out[20]: 
array([[1, 1, 0, 0],
       [0, 1, 0, 0],
       [0, 1, 1, 1],
       [1, 1, 1, 1]])

In [21]: [bool2int(x[::-1]) for x in a]
Out[21]: [12, 4, 7, 15]

这篇关于二进制数组numpy的列出整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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