我需要生成一个列表,其中包含固定长度的随机字母数字字符串。它将类似于:list = ['ag5','5b9','c85']
我可以使用随机数字制作列表,但是我无法制作出既有数字又有字母的字符串。列表将具有固定长度(例如100项) )。我正在使用python 3。
答案 0 :(得分:5)
string.digits
和string.ascii_lowercase
可以为您提供一组字母数字字符。然后,您可以在列表推导中使用random.choice
来生成列表:
from random import choice
from string import digits, ascii_lowercase
chars = digits + ascii_lowercase
L = ["".join([choice(chars) for i in range(2)]) for j in range(100)]
print(L)
答案 1 :(得分: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']
所有这些都至少有一个数字和至少一个小写字母。
答案 2 :(得分:-1)
如果您愿意,我建议最小长度为3的hashids
和自定义盐:
codes = [hasher.encode(i) for i in range(100)] # assuming hasher = hashids.Hashids('', 3)
答案 3 :(得分:-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']