我试图将二进制值转换为每个 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] )
关于python - 将二进制数转换为包含每个二进制数的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33985791/