Python 生成一段随机字符串的三种写法
方法1
s1=''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10**7)) 1
方法2
for _ in range(10**7): s2 += random.choice(string.ascii_letters + string.digits) 1 2
方法3
s3=''.join(random.choices(string.ascii_letters + string.digits, k=10**7)) 1
运行时间对比
import time, random, string time_s_1 = time.time() s1=''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10**7)) time_e_1 = time.time() print('method 1:', str(time_e_1 - time_s_1)) s2='' time_s_2 = time.time() for _ in range(10**7): s2 += random.choice(string.ascii_letters + string.digits) time_e_2 = time.time() print('method 2:', str(time_e_2 - time_s_2)) time_s_3 = time.time() s3=''.join(random.choices(string.ascii_letters + string.digits, k=10**7)) time_e_3 = time.time() print('method 3:', str(time_e_3 - time_s_3)) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
下面是输出的运行时间:
method 1: 9.464683055877686 method 2: 18.667069911956787 method 3: 2.693830728530884 1 2 3
结论:系统内置函数random.choices速度最快
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16