# python集合运算案例

python生成不重复随机数放在列表中的效率比较

import random
import time

def RandomNumbers(number, start, end):
'''使用列表来生成number个介于start和end之间的不重复随机数'''
data = []
n = 0
while True:
element = random.randint(start, end)
if element not in data:
data.append(element)
n += 1
if n == number - 1:
break
return data
def RandomNumbers1(number, start, end):
'''使用列表来生成number个介于start和end之间的不重复随机数'''
data = []
while True:
element = random.randint(start, end)
if element not in data:
data.append(element)
if len(data) == number:
break
return data
def RandomNumbers2(number, start, end):
'''使用集合来生成number个介于start和end之间的不重复随机数'''
data = set()
while True:
if len(data) == number:
break
return data
start = time.time()
for i in range(1000):
RandomNumbers(1000, 1, 10000)
print('Time used:', time.time()-start)

start = time.time()
for i in range(1000):
RandomNumbers1(1000, 1, 10000)
print('Time used1:', time.time()-start)

start = time.time()
for i in range(1000):
RandomNumbers2(1000, 1, 10000)
print('Time used2:', time.time()-start)


==================== RESTART: C:/Users/xuzm/Desktop/比较.py ====================
Time used: 24.607422828674316
Time used1: 24.069069623947144
Time used2: 4.816216945648193
>>> 

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120