我需要生成一个具有固定长度的随机字母数字字符串的列表。它会是这样的:list = ['ag5','5b9','c85']
,我可以用随机数来生成列表,但是我无法计算出字符串,它同时包含数字,letters.The列表将有固定的长度(比如100项)。我正在使用python 3。
发布于 2015-12-27 22:25:02
我想,你想要的东西如下:
>>> 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']
https://stackoverflow.com/questions/34484972
复制相似问题