Python 生成一段随机字符串的三种写法

Joyliness 2018-11-12

方法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速度最快

Python 生成一段随机字符串的三种写法

相关推荐