我今天剛開始在課堂上使用字典,現在我正在嘗試根據手機的鍵盤創建一個密碼。例如,我有這本字典:
2:['a','b','c']
現在,如果我想加密例如 a,輸出將是 21,其中兩個來自字典,1 來自其中 a 的位置,但我真的不知道該怎么做。這是我到目前為止嘗試過的,但沒有奏效。
def phoneCipher(string):
cipher = ''
keypad = {'2':['a','b','c'],'3':['d','e','f'],'4':['g','h','i'],'5':['j','k','l'],'6' : ['m','n','o'],
'7':['p','q','r','s'],'8':['t','u','v'],'9':['w','x','y','z']}
for i in string:
if i in keypad:
position = keypad.find(i)
cipher = keypad[i] position
return cipher
uj5u.com熱心網友回復:
如果您真的想這樣做,那么正如@Barmar所說,當您檢查i in keypad它是否檢查字典的鍵時,即數字值。所以這永遠不會匹配。似乎您還想獲取字串中每個字符的密碼,因此需要兩個嵌套回圈。我認為這可以按照您的意愿進行。
def phoneCipher(string):
cipher = ''
keypad = {'2':['a','b','c'],'3':['d','e','f'],'4':['g','h','i'],'5':['j','k','l'],'6' : ['m','n','o'],
'7':['p','q','r','s'],'8':['t','u','v'],'9':['w','x','y','z']}
for i in string:
for key in keypad:
if i in keypad[key]:
#position = keypad[key].index(i) # note its index not find, but we don't actually need it
cipher = key
return cipher
盡管效率極低,但我建議您將字典顛倒過來,因此它是字母對數字而不是數字對字母。
所以也許:
def phoneCipher2(string):
cipher = ''
keypad = {'a':'2','b':'2','c':'2',
'd':'3','e':'3','f':'3',
'g':'4','h':'4','i':'4',
'j':'5','k':'5','l':'5',
'm':'6','n':'6','o':'6',
'p':'7','q':'7','r':'7','s':'7',
't':'8','u':'8','v':'8',
'w':'9','x':'9','y':'9','z':'9',}
for i in string:
cipher = keypad[i]
return cipher
uj5u.com熱心網友回復:
您可以執行兩個基本選項。一種是迭代其中的每個list,dict然后迭代list并查看值是否在其中。另一種是有正向和反向dict。這會占用更多記憶體,但速度更快。
選項list1迭代dict
def phoneCipher(string):
cipher = ''
keypad = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']}
for c in string:
for number, letters in keypad.items():
if c in letters:
cipher = number str(letters.index(c))
return cipher
選項 2使用反向查找dict
keypad = {'2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'],
'5': ['j', 'k', 'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'],
'8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z']}
# Creating a reverse dict should be done only once and saved for future/repeated use
reverse_lookup = dict()
for number, letters in keypad.items():
for index, letter in enumerate(letters):
reverse_lookup[letter] = number str(index)
def phoneCipher(string):
return ''.join(map(lambda char: reverse_lookup[char], string))
uj5u.com熱心網友回復:
試試這個,
def phoneCipher(string):
cipher = ''
keypad = {'2':['a','b','c'],'3':['d','e','f'],'4':['g','h','i'],'5':['j','k','l'],'6' : ['m','n','o'],
'7':['p','q','r','s'],'8':['t','u','v'],'9':['w','x','y','z']}
for i in string:
for key in keypad:
if i in keypad[key]:
cipher = key
continue
return cipher
phoneCipher("ishan")
輸出 -
47426
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/465129.html
上一篇:如何改變字典的位置?[復制]
