输出Python Dictionary'Values'作为二进制格式

时间:2016-11-10 19:02:24

标签: python dictionary

我试图解决这个问题一段时间。寻找简单的答案但无济于事。任何帮助非常感谢。我创建了一个python字典,并尝试将值的输出格式化为二进制数据。换句话说,对于字典中的每个字符串值,我想输出其二进制值。我的代码和我得到的错误如下。

pigpen = {}
pigpen['a'] = 'ETL'
pigpen['b'] = 'ETM'
pigpen['c'] = 'ETR'
pigpen['d'] = 'EML'
pigpen['e'] = 'EMM'
pigpen['f'] = 'EMR'
pigpen['g'] = 'EBL'
pigpen['h'] = 'EBM'
pigpen['i'] = 'EBR'
pigpen['j'] = 'DTL'
pigpen['k'] = 'DTM'
pigpen['l'] = 'DTR'
pigpen['m'] = 'DML'
pigpen['n'] = 'DMM'
pigpen['o'] = 'DMR'
pigpen['p'] = 'DBL'
pigpen['q'] = 'DBM'
pigpen['r'] = 'DBR'
pigpen['s'] = 'EXT'
pigpen['t'] = 'EXL'
pigpen['u'] = 'EXR'
pigpen['v'] = 'EXB'
pigpen['w'] = 'DXT'
pigpen['x'] = 'DXL'
pigpen['y'] = 'DXR'
pigpen['z'] = 'DXB'

import binascii
str = pigpen.values()
print ' '.join(format(ord(string), 'b') for string in str)

Traceback (most recent call last):
  File "pigpen_build.py", line 62, in <module>
    print ' '.join(format(ord(string), 'b') for string in str)
  File "pigpen_build.py", line 62, in <genexpr>
    print ' '.join(format(ord(string), 'b') for string in str)
TypeError: ord() expected a character, but string of length 3 found
>>> 

2 个答案:

答案 0 :(得分:0)

您要求ord根据字符串中的3个字符查找值。有关the ord function here.的详细信息在for循环中,您正在对列表进行交互,因此扩展的代码就像这样。

for s in ['ABC','CDE','FGH']:
  print s+', ',

哪个会输出,ABC, CDE, FGH。要修复此问题,请在实际字符串上放置另一个for循环,或将原始列表合并为一个字符串。

1)另一个for循环。

print ' '.join(format(ord(string), 'b') for string in (''.join(s for s in str)))

2)实际字符串。

str = ''.join(s for s in str)
print ' '.join(format(ord(stirng), 'b') for string in str)

答案 1 :(得分:0)

@Preston用更好的答案打败了我,但这里有一个不使用嵌套列表理解的解决方案。

binary_translation = []
for string in a:
    for char in string:
        binary_translation.append(''.join(format(ord(char), 'b')))