簡體   English   中英

使用每個二進制數將二進制轉換為數組

[英]Convert a binary to an array with each binary number

我正在嘗試將每個1/0的二進制值轉換為列表,但是我得到默認的二進制值而不是列表。

我有一個字符串,我將每個字符轉換為二進制,它為我提供了一個列表,其中包含每個字符的字符串。 現在,我試圖將每個字符串拆分為值0/1的整數,但是我什么也沒得到。

# 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)) 

當您想同時加入列表理解功能時,可以這樣進行:

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

嘗試;

bin = [int(x)for s in c for x in s]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM