Tuesday, December 23, 2008

python提取列表里重复数据性能优化

列表内容限于文本或者数字。

def foo(alist):
    """
        extract the repeat item out of a list
    """
    d = dict()
    sd = dict()
    for i in alist:
        if id(i) not in d:
            d[id(i)] = ''
        else:
            sd[i] = ''
    return sd.keys()

因为在python里相同的串或者数字为同一个对象,所以使用id来作为hash算法,放到字典里去做对比,而不是直接对比内容本身,因而提高一定的性能。


Reactions

est | 2008-12-23 19:25 | IP:211.95.166.158

[x for x in set([1,2,3,4])]


est | 2008-12-23 19:26 | IP:211.95.166.158

貌似少打了一个。。。

>>> [x for x in set([1,1,1,2,3,4,4,5,6,'a','a','b', u'd'])]
['a', 1, 2, 3, 4, 5, 6, 'b', u'd']


Add a reaction

About You

Comment