开发者

pythonic way to map set of strings to integers

开发者 https://www.devze.com 2023-02-16 04:35 出处:网络
Is there shorter way to do this? g_proptypes = { \'uint8\' : 0 \'sint8\' : 1, \'uint16\' : 2, \'sint16\' : 3,

Is there shorter way to do this?

g_proptypes = {
    'uint8' : 0
    'sint8' : 1,
    'uint16' : 2,
    'sint16' : 3,
    'uint32' : 4,
... # more strings
}

The dict is necessary as I'll have the strin开发者_开发技巧g with me and need to find the corresponding integer.


If you have your strings in an iterable you can do:

g_proptypes = dict((string, i) for i, string in enumerate(string_list))


>>> lst = ['uint8','sint8','unit16','sint16','uint32','etc']

>>> g_proptypes = dict(map(reversed,enumerate(lst)))

>>> g_proptypes

{'sint16': 3, 'unit16': 2, 'uint8': 0, 'etc': 5, 'sint8': 1, 'uint32': 4}


you can do this if the integers are sequential : http://codepad.org/o7ryZ09O

myList = ['uint8','sint8','uint16','sint16','uint32']
myStr = 'uint16'
myNum = myList.index(myStr);
print myNum;
0

精彩评论

暂无评论...
验证码 换一张
取 消