菜鸟笔记
提升您的技术认知

python中列表去重,保留原先顺序的八种方法-ag真人游戏

有道面试题: 将列表  l = [3, 1, 2, 1, 3, 4]去掉重复的元素,但保留原先顺序。 最后结果应该是:[3, 1, 2, 4]

如果不保留顺序的去重,很好处理,比如用set

>>> l = [3, 1, 4, 2, 3]
>>> list(set(l))
[1, 2, 3, 4]

如果要保留原先顺序不变,同样也有很多种方法:

方法一: 

>>> l = [3, 1, 2, 1, 3, 4]
>>> t = []
>>> for i in l:
...     if not i in t:
...         t.append(i)
>>> t
[3, 1, 2, 4]

方法二: 

>>> l = [3, 1, 2, 1, 3, 4]
>>> t = []
>>> [t.append(i) for i in l if not i in t ]
[none, none, none, none]
>>> t
[3, 1, 2, 4]

方法三:

>>> l = [3, 1, 2, 1, 3, 4]
>>> t = list(set(l))
>>> t
[1, 2, 3, 4]
>>> t.sort(key=l.index)
>>> t
[3, 1, 2, 4]

方法四:

>>> l = [3, 1, 2, 1, 3, 4]
>>> t = []
>>> for i,v in enumerate(l):
...     if l.index(v) == i:
...         t.append(v)
>>> t
[3, 1, 2, 4]

方法五: 

>>> l = [3, 1, 2, 1, 3, 4]
>>> t = {}.fromkeys(l).keys()
>>> t
[1, 2, 3, 4]
>>> t.sort(key=l.index)
>>> t
[3, 1, 2, 4]

方法六:

>>> l = [3, 1, 2, 1, 3, 4]
>>> t = l[:]
>>> for i in l:
...     while t.count(i) > 1:
...         del t[t.index(i)]
>>> t
[2, 1, 3, 4]
>>> t.sort(key=l.index)
>>> t
[3, 1, 2, 4]

方法七:

>>> l = [3, 1, 2, 1, 3, 4]
>>> t = sorted(set(l), key=l.index)
>>> t
[3, 1, 2, 4]

方法八:

>>> l = [3, 1, 2, 1, 3, 4]
>>> func = lambda l,i: l if i in l else l   [i]
>>> t = reduce(func, [[], ]   l)
>>> t
[3, 1, 2, 4]

备注: 

  • lambda l,i: l if i in l else l [i]   # 如果元素在列表中,那么返回列表本身,不在的话l [i]
  • [[], ] l                                         # 等价于 [[], l],方便后面计算
网站地图