在Python中生成固定长度的随机字符串列表

5

我需要生成一个固定长度的随机字母数字字符串列表,例如:list = ['ag5','5b9','c85'] 我可以使用随机数生成数字列表,但是我不知道如何生成既有数字又有字母的字符串。该列表将有固定的长度(比如100个元素),我正在使用Python 3。


列表中每个元素的大小是多少? - Iron Fist
1
尝试在谷歌上搜索“Python生成随机字母数字字符串”。 - intboolstring
@intboolstring...不要安静...操作者想要字母数字混合。 - Iron Fist
2
这些代码应该是唯一的吗? - Malik Brahimi
请在提问前先进行谷歌搜索。你已经尝试过什么了吗? - Vlad M
显示剩余3条评论
4个回答

11

要获取字母数字字符集,您可以从 string 模块中组合常量。然后,您可以在列表推导式中使用 random.choice() 生成列表:

from random import choice
from string import ascii_lowercase, digits

chars = ascii_lowercase + digits
lst = [''.join(choice(chars) for _ in range(2)) for _ in range(100)]
print(lst)

0

由于每个字符串都必须包含字母和数字,我们需要进行比平常更多的工作。我们可以继续生成随机单词,并仅接受满足约束条件的单词,或者我们可以通过构建符合约束条件的字符集合来解决。

from random import choice, shuffle
from string import digits, ascii_lowercase

def gen_word(N, min_N_digits, min_N_lower):
    choose_from = [digits]*min_N_dig + [ascii_lowercase]*min_N_low
    choose_from.extend([digits + ascii_lowercase] * (N-min_N_low-min_N_dig))
    chars = [choice(bet) for bet in choose_from]
    shuffle(chars)
    return ''.join(chars)

def gen_word_rejection(N, min_N_digits, min_N_lower):
    bet = digits + ascii_lowercase
    while True:
        word = ''.join([choice(bet) for i in range(N)])
        if (sum(c.isdigit() for c in word) >= min_N_digits and
            sum(c.islower() for c in word) >= min_N_lower):
            return word

这给了我

>>> [gen_word(3, 1, 1) for i in range(5)]
['mb6', 'g4b', 'y5g', '28p', 'ki2']
>>> [gen_word_rejection(3, 1, 1) for i in range(5)]
['y37', 'dr0', 'w1z', 'h2a', 'i6r']

所有这些都至少有一个数字和至少一个小写字母。


-1

如果您需要,我建议使用hashids,并设置最小长度为三个字符和自定义盐:

codes = [hasher.encode(i) for i in range(100)] # assuming hasher = hashids.Hashids('', 3)

因为这是一种哈希技术,如果您继续使用相同的盐值,结果哈希码将不会非常随机。我强烈建议使用随机生成的盐值。 - Malik Brahimi

-1

我想你想要的是以下内容:

>>> import string
>>> import random
>>> L1 = []
>>> my_chars = string.ascii_lowercase + string.digits #list of alphanumeric characters
>>> while(len(L1)<100): #To keep iterating until len(L1)=100
    s = random.sample(my_chars,3) #Pick a sample(list) of three characters len from chars list
    if not all(t in string.digits for t in s) and not all(t in string.ascii_lowercase for t in s): #Check if these characters are neither only digits nor letters, only mix of both will be allowed
        L1.append(''.join(s)) #concatenate the characters to form the string and add it to list L1


>>> len(L1)
100
>>> L1
['f3m', 'gw2', '9ua', 'm4r', 'fv5', 'jw1', 'd1b', 'lh1', 'i61', '53m', 'j6y', 'fg6', '90d', 'xz1', 'n9f', 'k6r', '31b', 'm8w', '8w1', 'h5q', 'h3d', 'ju2', 'q1i', '6ci', '07m', '40c', 's0h', 'q1p', 'u2o', 'r4g', '6gq', 'rj4', '08x', 'yr6', 'il7', '21w', 'v3q', 'kv9', 'e4i', 'g3o', 'r2p', 'nl7', 'k8h', 'by9', 'qd1', 't71', 'x8f', 'uq3', 'k2z', '5i7', '7pc', 'd68', '6n0', '81y', 'c34', 'la0', 'a0c', '1d9', '7oi', 'z7x', '8l9', '0te', 'e9b', '2yp', '17h', 'vm1', 'vm1', 'ow9', '1ma', 'y7q', '7wa', 'a6b', '9uo', '5t2', 'i40', 'ja1', '16v', '0fe', '6bc', 'ek3', 'th6', '26g', 'a9n', 'fo5', '3hg', '4wz', 'v6z', 'r7b', '9cr', 'a0s', '8yp', 'v0f', 'es4', '8do', 'd0e', 'o6z', 'x3q', 'qw3', 'gi0', '0eg']

是的,它现在更像我想要的那样运行。我现在已经加入了ascii_uppercase。谢谢。 - Aman
刚刚发现这段代码有问题。列表应该包含100个字母数字字符串作为列表元素。但每次运行它时,列表长度都会随机变化,大多数情况下在50到70之间。我的意思是有时列表包含53个项目,有时是68或更多。range(100)中的i应该生成100个字符串,但我不明白为什么没有发生。你能帮忙吗? - Aman
@Aman...是的,我已经更新了答案。实际上应该使用while循环。 - Iron Fist
为什么要点踩?请留下评论。 - Iron Fist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接