如何用Pythonic的方法求一个字符的往后两位字符?
PHP中文网
PHP中文网 2017-04-17 13:03:37
0
5
636

想建立如下映射关系:

'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中文网

认证0级讲师

reply all(5)
左手右手慢动作

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.

左手右手慢动作
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

左手右手慢动作

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

Sit back and wait for the master...

迷茫
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

巴扎黑
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 :(

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template