Convert alphabet letters to number in Python

后端 未结 16 1803
慢半拍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:48

    If the goal is to transform only the letters abcd....xyz and ABCD....XYZ , I would use a function:

    from string import letters
    def rank(x, d = dict((letr,n%26+1) for n,letr in enumerate(letters[0:52]))):
        return d[x]
    

    I’ve written [0:52] because my Python 2.7 version displays the value

    *ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz*ƒŠŒŽšœžŸÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ

    for the string.letters argument.

    Because the parameter d receives a value as a default argument, the calculus of this value is performed only once, at the moment when the definition of the function is executed to produce the function object. So, the function can then be used without this value to be calculated again, even if the function is appealed three thousand times.

    By the way, lower() isn’t used again for each appeal of the function. The case of upper letters has been treated during the construction of the default argument.

    .

    One example of use:

    word = 'supercalifragilisticexpialidocious'
    print ''.join( letter if rank(letter)%3!=0 else '.' for letter in word)
    

    result:

    s.pe..a....ag...st..e.p.a..d.....s

    .

    It can be used with map() too :

    print map(rank,'ImmunoElectroPhoresis')
    

    result:

    [9, 13, 13, 21, 14, 15, 5, 12, 5, 3, 20, 18, 15, 16, 8, 15, 18, 5, 19, 9, 19]

提交回复
热议问题