使用每个二进制数将二进制数转换为数组 [英] Convert a binary to an array with each binary number

查看:295
本文介绍了使用每个二进制数将二进制数转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将每个1/0的二进制值转换为列表,但是我得到默认的二进制值而不是列表.

I am trying to convert a binary value to a list with each 1/0 but I get the default binary value and not the list.

我有一个字符串,我将每个字符转换为二进制,它为我提供了一个列表,其中包含每个字符的字符串.现在,我试图将每个字符串拆分为值0/1的整数,但我什么也没得到.

I have a string, I convert each character in binary and it gives me an list with a string for each character. Now I am trying to split each string into ints with the value 0/1 but I can't get anything.

# if message = "CC"
message="CC"

# just a debug thing
for c in message:
    asci = ord(c)
    bin = int("{0:b}".format(asci))
    print >> sys.stderr, "For %c, asci is %d and bin is %d" %(c,asci,bin)

c = ["{0:b}".format(ord(c)) for c in message]
# c = ['1000011', '1000011']
bin = [int(c) for c in c]
#bin should be [1,0,0,0,0,1,1,1,0,0,0,0,1,1]
# but I get [1000011, 1000011]
print >> sys.stderr, bin

推荐答案

如果您有此内容:

c = ['1000011', '1000011']

您要实现这一目标:

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

您可以这样做:

modified_list=[int(i) for  element in c for i in element]

或者您可以使用itertools.chain

from itertools import chain
modified_list=list(chain(*c)) 

当您想同时加入列表理解功能时,可以通过以下方式做到这一点:

As you want to join both the list comprehension, you can do it this way:

bin= list( chain( *["{0:b}".format(ord(c)) for c in message] )

这篇关于使用每个二进制数将二进制数转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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