Python 2.7:字典(switch语句)值

时间:2015-05-25 19:27:48

标签: python-2.7 dictionary hex

Python 2.7:字典(switch语句)值

我将十六进制值的十六进制值解码(字符串数组),并且我想使用字典来存储结果浮点值,但我不知道如何操作。 为了快速解决问题,我使用了if-elif语句来执行此操作 - 是否可以使用字典来完成此操作?到目前为止,这是我的代码:

enter image description here

# assume data is in IEEE 754 format
import struct
from binascii import unhexlify

inputData  = ['41', 'b8', '00', '00', '40', '5d', '70', 'a4', '40', '07', 'ae', '14']
outputData = {'first': 0.0, 'second': 0.0, 'third': 0.0}
for offset in [0, 4, 8]:
    valueBytes = inputData[offset:offset+4]
    value      = struct.unpack('>f',unhexlify(''.join(valueBytes)))[0]
    print valueBytes, '=>', value
    if offset == 0:
        outputData['first']  = value
    elif offset == 4:
        outputData['second'] = value
    elif offset == 8:
        outputData['third'] = value
    # could use if-else here but I'd like a dictionary
    #options = {
    #    0 : outputData['first']  = value,
    #    4 : outputData['second'] = value,        
    #    8 : outputData['third']  = value
    #    }[offset]

1 个答案:

答案 0 :(得分:1)

Pyhton没有开关声明。在大多数情况下,你会使用另一种语言的开关,你可以在python中使用dict查找:

inputData  = ['41', 'b8', '00', '00', '40', '5d', '70', 'a4', '40', '07', 'ae', '14']
outputData = {'first': 0.0, 'second': 0.0, 'third': 0.0}
offset_to_key = {0: 'first', 4: 'second', 8: 'third'}
for offset in [0, 4, 8]:
    valueBytes = inputData[offset:offset+4]
    value      = struct.unpack('>f',unhexlify(''.join(valueBytes)))[0]
    print valueBytes, '=>', value
    outputData[offset_to_key[offset]] = value

另一种可能性是将密钥指定为循环变量:

inputData  = ['41', 'b8', '00', '00', '40', '5d', '70', 'a4', '40', '07', 'ae', '14']
outputData = {'first': 0.0, 'second': 0.0, 'third': 0.0}
for offset, dictkey in zip([0, 4, 8], ['first', 'second', 'third']):
    valueBytes = inputData[offset:offset+4]
    value      = struct.unpack('>f',unhexlify(''.join(valueBytes)))[0]
    print valueBytes, '=>', value
    outputData[dictkey] = value