search

Home  >  Q&A  >  body text

如何用Pythonic的方法求一个字符的往后两位字符?

想建立如下映射关系:

'a' -->  'c'   
'b' -->  'd'
    ...
'y' -->  'a'
'z' -->  'b'

在C中我们可以很轻松的用加法实现, 但是换到python, 我想到了以下方法:

from string import ascii_lowercase as al

my_dict = dict(zip(al, [chr((ord(x)-95)%26+97) for x in al]))

看起来一点都不cool, 主要是求字符的后两位字符那里处理的不好, 大伙有没有更pythonic点的方法呢?

PHP中文网PHP中文网2866 days ago660

reply all(5)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 13:05:37

    I don’t know why you still need to use chr and ord?? What I mean is: your requirement is very simple. You already know the 26 letters, but you are wrong by 2 digits.

    >>> from string import ascii_lowercase as keys
    >>> vals = keys[2:] + keys[:2]
    >>> dict(zip(keys, vals))
    {'a': 'c', 'c': 'e', 'b': 'd', 'e': 'g', 'd': 'f', 'g': 'i', 'f': 'h', 'i': 'k', 'h': 'j', 'k': 'm', 'j': 'l', 'm': 'o', 'l': 'n', 'o': 'q', 'n': 'p', 'q': 's', 'p': 'r', 's': 'u', 'r': 't', 'u': 'w', 't': 'v', 'w': 'y', 'v': 'x', 'y': 'a', 'x': 'z', 'z': 'b'}
    

    The requirement has been fulfilled. I think the key to your question may not be what I answered.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:05:37

    from string import maketrans 
    int = "abcdefghijklmnopqrstuvwxyz"
    out = "cdefghijklmnopqrstuvwxyzab"
    
    b = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
    
    trans_int_out = maketrans(int, out)
    print b.translate(trans_int_out)
    

    Python Challenge Level 1 Walkthrough

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:05:37

    dict(zip(al, map(lambda x : chr((ord(x) - 95) % 26 + 97), al)) )

    Sit back and wait for the master...

    reply
    0
  • 迷茫

    迷茫2017-04-17 13:05:37

    a = 'abcdefghijklmnopqrstuvwxyz'
    b = [chr(((ord(x) - 95) % 26) + 97) for x in a]
    >>> b
    ['c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b']
    

    Haha, there is no inspection part

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 13:05:37

    from string import ascii_lowercase
    from itertools import cycle
    from itertools import islice
    from itertools import izip
    
    N = 2
    
    dict(izip(ascii_lowercase,
              islice(cycle(ascii_lowercase),
                     N,
                     None)))
    

    Not Pythonic at all :(

    reply
    0
  • Cancelreply