我想在字母上附加一个随机数,我的意思是,任何字母都将被分配一个随机数。问题是那个数字不能是2个字母的相同数字。另一个问题是:
目前,我有:
Input: A
Output: 36
Input: AA
Output: 3614
我想要的是:
Input: AA
Output: 3636
这是我的代码:
from random import randint
cifrar = input("Escriba el texto: ")
diction = ['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']
for diction in cifrar:
a = randint(0, 36)
print(a)
Here is an image of my current input and output
在此图像示例中,我想要的是相同的数字,因为所有都是A
答案 0 :(得分:1)
您似乎认为的是dictionary,实际上只是一个list。此外,您实际上并没有使用该列表,因为循环在每次迭代时都会为变量diction
分配一个新值。然后,为输入的每个字母打印一个随机数。
您想要的是真正使用词典在每个字母与随机数之间创建 static 映射:
import string
import random
diction = dict(zip(string.ascii_lowercase, random.sample(range(36), 26)))
cifrar = input("Escriba el texto: ")
for letter in cifrar:
print(diction.get(letter.lower(), letter))
示例运行:
Escriba el texto: AA!BB$CC
14
14
!
3
3
$
24
24
答案 1 :(得分:0)
也许是这样吗?
from random import shuffle
numbers = [i for i in range(26)]
letters = [chr(ord('a') + i) for i in numbers]
创建字母和数字列表
numbers = shuffle(numbers)
随机排序并合并
print(zip(letters, numbers))