对python中两种列表元素去重函数性能的比较方法

测试函数:

第一种:list的set函数

第二种:{}.fromkeys().keys()

测试代码:

#!/usr/bin/python
#-*- coding:utf-8 -*-
import time
import random
 
l1 = []
leng = 10L
for i in range(0,leng):
 temp = random.randint(1,10)
 l1.append(temp)
print '测试列表长度为:',leng
#first set
last = time.clock()
l2 = list(set(l1))
print l2
now = time.clock()
print '第一种:',now-last
 
#second
last = time.clock()
l2 = {}.fromkeys(l1).keys()
print l2
now = time.clock()
print '第二种:',now-last

测试结果:

对python中两种列表元素去重函数性能的比较方法

我们可以看出,当测试列表长度很短时,使用第二种方法较快,在1000时,第一种性能已经超过第二种了,列表越长,第一种方法优势越明显。当频繁的对短列表进行去重时(长度<=1000)建议使用第二种方法,当长度超过1000时建议使用第二种方法。

但归根结底,建议不要用python进行大规模的数据计算,建议使用matlab、或者python的matlab库,毕竟专业的还是厉害。