5

实现python中如何列表去重不打乱顺序的方法

 2 years ago
source link: https://www.huhexian.com/15712.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

实现python中如何列表去重不打乱顺序的方法

青山 2021-12-0810:18:28评论621字

我们在使用python编程中,我们有的时候需要用到列表去重的时候,但是我们经常会遇到去重之后,原本列表的顺序打乱了的情况。很多小伙伴不知道如何在去重的同时又不打乱顺序,下面就来给大家分享一下python中如何列表去重不打乱顺序的方法。

实现python中如何列表去重不打乱顺序的方法

针对此问题,我整理了三种列表去重但不打乱顺序的方法:

1、使用集合set去重

  1. l1 = ['b','c','d','b','c','a','a']
  2. l2 = sorted(set(l1),key=l1.index)
  3. print l2

2、使用用sort()中的key字段进行设定

  1. #随便创建一个有重复数据的列表
  2. lt1 = [0,1,2,3,4,4,5,5,6,12,6,7,7,8,8,8,8,9,9,10,11,10,64]
  3. #把列表二次转换
  4. lt = list(set(lt1))
  5. #index()是为了从列表中找到某个值第一项的索引位置,
  6. #sort(key,reverse)是改变原来列表的元素位置,不会生成一个新列表,reverse默认是true,就是升序。
  7. lt.sort(key=lt1.index)
  8. print(lt)

3、使用reduce()函数去重

  1. list = [1,4,3,3,4,2,3,4,5,6,1]
  2. func = lambda x,y:x if y in x else x + [y] In
  3. reduce(func, [[], ] + list)
  4. 输出结果:
  5. [1, 4, 3, 2, 5, 6]

以上就是python中三种列表去重但不打乱顺序的方法,有需要的朋友可以直接套用。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK