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:
        data.add(random.randint(start, end))
        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
>>> 

可见:
append方法对空裂变追加元素的方法效率远不及add方法

你可能感兴趣的:(python)