gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:18:49 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com