【问题标题】:Convert a binary to an array with each binary number将二进制转换为包含每个二进制数的数组
【发布时间】:2016-03-03 07:59:02
【问题描述】:

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

【问题讨论】:

    标签: python string list binary list-comprehension


    【解决方案1】:

    如果你有这个:

    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(i) for element in ["{0:b}".format(ord(c)) for c in message] for i in element]
    【解决方案2】:

    试试;

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 2011-01-08
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 2017-01-31
      相关资源
      最近更新 更多