我需要生成一个固定长度的随机字母数字字符串列表,例如:list = ['ag5','5b9','c85']
我可以使用随机数生成数字列表,但是我不知道如何生成既有数字又有字母的字符串。该列表将有固定的长度(比如100个元素),我正在使用Python 3。
我需要生成一个固定长度的随机字母数字字符串列表,例如:list = ['ag5','5b9','c85']
我可以使用随机数生成数字列表,但是我不知道如何生成既有数字又有字母的字符串。该列表将有固定的长度(比如100个元素),我正在使用Python 3。
要获取字母数字字符集,您可以从 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)
由于每个字符串都必须包含字母和数字,我们需要进行比平常更多的工作。我们可以继续生成随机单词,并仅接受满足约束条件的单词,或者我们可以通过构建符合约束条件的字符集合来解决。
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']
所有这些都至少有一个数字和至少一个小写字母。
如果您需要,我建议使用hashids
,并设置最小长度为三个字符和自定义盐:
codes = [hasher.encode(i) for i in range(100)] # assuming hasher = hashids.Hashids('', 3)
我想你想要的是以下内容:
>>> 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']
while
循环。 - Iron Fist