python - 将二进制数转换为包含每个二进制数的数组

标签 python string list binary list-comprehension

我试图将二进制值转换为每个 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/

相关文章:

python - 在基于 celery+flask 的应用程序中,我需要为 Redis 安装什么?

Python 类型错误 : not enough arguments for format string in case of string %s

python - XML 标签文本到字符串忽略子标签但包含其文本

java - 字符串比较时获取空指针异常

python - 设计新类时如何打印联系人列表内容

python - and 运算符如何在 python 中工作?

python - 更有效地拆分列

python - 如何将 pandas value_counts 转换为 python 列表

list - 在 Prolog 中移动列表的元素

java - 最终列表或数组不会存储值