Convert alphabet letters to number in Python

后端 未结 16 1806
慢半拍i
慢半拍i 2020-11-28 05:09

How can the following be finished?

characters = [\'a\'\'b\'\'c\'\'d\'\'e\'\'f\'\'g\'\'h\'\'i\'\'j\'\'k\'\'l\'\'m\'\'n\'\'o\'\'p\'\'q\'\'r\'\'t\'\'u\'\'v\'\'w         


        
16条回答
  •  孤独总比滥情好
    2020-11-28 05:57

    If you are going to use this conversion a lot, consider calculating once and putting the results in a dictionary:

    >>> import string
    >>> di=dict(zip(string.letters,[ord(c)%32 for c in string.letters]))
    >>> di['c'] 
    3
    

    The advantage is dictionary lookups are very fast vs iterating over a list on every call.

    >>> for c in sorted(di.keys()):
    >>>    print "{0}:{1}  ".format(c, di[c])
    # what you would expect....
    

提交回复
热议问题