开发者

pythonic way to map set of strings to integers

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜