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算法,放到字典里去做对比,而不是直接对比内容本身,因而提高一定的性能。
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算法,放到字典里去做对比,而不是直接对比内容本身,因而提高一定的性能。
anonymous
Powered by
Reactions