我有伪随机生成字符串的代码。如何让我的代码输出25个随机字符串?
import random, string
special=['@','!','#','$','%','^','&','*','(',')','-','=','+','{','[','}',']',';',':','.','>','<',',','?','/',]
def id_generator(size=25, chars=string.ascii_uppercase + string.digits + random.choice(special) ):
return ''.join(random.choice(chars) for _ in range(size))
count = 0
def create_and_save_pseudorand():
for count in range(100):
return id_generator()
#print(id_generator())
create_and_save_pseudorand()
答案 0 :(得分:1)
我猜你要么
return [id_generator() for i in range(25)]
或将return
与yield
交换,然后使用:
for i in create_and_save_pseudorand():
print i
btw:你似乎混淆了字符串的长度和数量。哪一个应该是25?
答案 1 :(得分:0)
您的函数create_and_save_pseudorand
当前在返回第一个随机生成的字符串后停止。将return
更改为yield
以解决此问题。然后,您可以引入count
参数来确定要生成的随机字符串的数量。
def create_and_save_pseudorand(count):
for count in range(count):
yield id_generator()
然后,您可以使用
在控制台上打印结果print(list(create_and_save_pseudorand(25)))
示例输出:
['YAB*MT7CU29IY12QMVLNH4QI9', '1E1445DCN*5K7RZIJNKSIKX10', '53W06LS8NJEAE0X60MFW*ES*W', 'KK8WMRA3DMPRWWYQDG2M0ED0Q', 'ZFLBQ0V04Z*E1PVUF4DG04IJ2', '292VPZA3QDKLQ4UBTKJA3TY3H', 'A77426HK1HNZVMUT883CZABIX', 'I2M4I0IO9GRLNVAH9BWV52AYJ', '*VUU3DGHN79SG5XPELHCKSG29', '*KWM2BUPGIL4OV3TUZ7614OAT', '29JZ*Y59*O2SPL7CWL9BB3*5V', 'IVZ0MK0HPIVCJG039Y9GTM*ZH', 'ZF2QSL5VXYW6B4*FOE4KRL4LW', 'ZOK*Z508DD1JE5UYHLGGKORKS', 'L2XIBU8J3IMZO9Y2GFLQSB3W7', 'PA6ZJGXS4G96FDA771143TOMM', '2ZHK13LVZZQ878L1OR2LQ3TGV', 'QGYR2WNJ58GPD0*54CHI6AKAR', 'TKPBD27HQ0TZFFZCVMIDAYJX4', 'G7HH9YSZ4P3ETRGY9REB90WDC', 'G3PTXR376AGJHX4V5V4NRLL30', 'XHM1J0A5Z48*58RFVH9W3Z5*O', 'XHG8VGNF*YA4GBX1SBE*DVGKV', '39YNN1X719N*WZ9VBUPLTVC5P', 'XYMJ57DH*3WX589J9ZENGFP0O']