python 列表list去重
立即学习“Python免费学习笔记(深入)”;
一.{}.fromkeys(list).keys()
list2 = {}.fromkeys(list1).keys()
立即学习“Python免费学习笔记(深入)”;
二.set
list2 = list(set(list1))
立即学习“Python免费学习笔记(深入)”;
三.itertools.grouby
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids.sort()
it = itertools.groupby(ids)
for k, g in it:
print k
立即学习“Python免费学习笔记(深入)”;
四,笨方法
ids = [1,2,3,3,4,2,3,4,5,6,1]
news_ids = []
for id in ids:
if id not in news_ids:
news_ids.append(id)
print news_ids
这四种都有个特点,去重后元素排序变了,效率 据说第一种比第二种快一点
立即学习“Python免费学习笔记(深入)”;
五.索引再次排序 这种可以去重并且保持元素顺序
#要结果是[1, 4, 3, 2, 5, 6] 不要[1, 2, 3, 4, 5, 6]
ids = [1,4,3,3,4,2,3,4,5,6,1]
news_ids = list(set(ids))
news_ids.sort(key=ids.index)
print news_ids #[1, 4, 3, 2, 5, 6]
立即学习“Python免费学习笔记(深入)”;
六:Reduce
ids = [1,4,3,3,4,2,3,4,5,6,1]
func = lambda x,y:x if y in x else x + [y]
print reduce(func, [[], ] + ids)#[1, 4, 3, 2, 5, 6]
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号