如何制作仅使用一次的随机唯一数

时间:2019-04-30 18:07:47

标签: python python-3.x

我正在创建一个程序,该程序将生成一个随机代码列表,并将文本转换为代码。我在弄清楚如何使代码等于列表中的单个随机字母时遇到麻烦。

这是我到目前为止的代码:

loop = 0
while loop < 24:
    numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]
    letters = ['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']
    random.shuffle(numbers)
    random.shuffle(letters)
    print(numbers, "=", letters)
    loop = loop + 1
    if loop == 24:
        print("test")

它正在输出如下内容:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24] = ['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']

理论上,它在输出时应该看起来像这样: 1 = g,2 = w,3 = k,依此类推。

2 个答案:

答案 0 :(得分:0)

以下是我在评论中说的一个例子:

from random import shuffle
from string import ascii_lowercase

letters = list(ascii_lowercase)
shuffle(letters)

list(enumerate(letters))

上面代码的输出是这样的:

>>> from pprint import pprint
>>> pprint(list(enumerate(letters)))
[(0, 'z'),
 (1, 'a'),
 (2, 's'),
 (3, 'y'),
 (4, 'o'),
 (5, 'h'),
 (6, 'p'),
 (7, 'v'),
 (8, 'l'),
 (9, 'r'),
 (10, 'e'),
 (11, 'i'),
 (12, 'm'),
 (13, 'g'),
 (14, 'b'),
 (15, 'q'),
 (16, 'n'),
 (17, 'u'),
 (18, 'd'),
 (19, 'k'),
 (20, 'x'),
 (21, 'c'),
 (22, 'j'),
 (23, 't'),
 (24, 'f'),
 (25, 'w')]
>>> 

答案 1 :(得分:0)

您可以使用string模块和random-enumerate为低位ascii来回混排的值创建字典查找。

from string import ascii_lowercase
import random
atoz = list(ascii_lowercase)
random.shuffle(atoz)

# add the index:character translation    
d = { idx:char for idx,char in enumerate(atoz) }

# update with the reverse translation:
d.update( {c:k for k,c in d.items() } )
print(d)

输出:

{0: 'w', 1: 'e', 2: 'v', 3: 'r', 4: 'm', 5: 'n', 6: 'z', 7: 'x', 8: 'g', 
 9: 'j', 10: 'p', 11: 'y', 12: 'q', 13: 'c', 14: 'u', 15: 'a', 16: 't', 
17: 'l', 18: 'f', 19: 's', 20: 'h', 21: 'i', 22: 'b', 23: 'o', 24: 'k', 
25: 'd', 
'w': 0, 'e': 1, 'v': 2, 'r': 3, 'm': 4, 'n': 5, 'z': 6, 'x': 7, 'g': 8, 
'j': 9, 'p': 10, 'y': 11, 'q': 12, 'c': 13, 'u': 14, 'a': 15, 't': 16, 
'l': 17, 'f': 18, 's': 19, 'h': 20, 'i': 21, 'b': 22, 'o': 23, 'k': 24, 'd': 25}

使用该词典进行翻译:

def word_to_ints(word, d):
    return [d.get(c,c) for c in word.lower()]

def ints_to_word(ints, d):
    return ''.join( (d.get(n,n) for n in ints) )

k = word_to_ints("Translate me", d )

print(k, "=", ints_to_word(k, d))

输出:

[16, 3, 15, 5, 19, 17, 15, 16, 1, ' ', 4, 1] = translate me

Doku: