Posted in Python onOctober 17, 2019
本文实例讲述了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集合常见运算案例解析
- Author -
eacxzm声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@