python列表去重不改原序的两种pythonic方法

# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''给定一个列表,去重,并保证元素的原始次序不变'''

alist = [1, 1, 1, 1, 2, 3, 4, 4, 4, 5, 6, 1, 2, 2]

# 方法一:列表推导式
blist = []
clist = [blist.append(i) for i in alist if not i in blist]
print(blist)  # [1, 2, 3, 4, 5, 6]
# 注意: clist 多余,没有用
print(clist)  # [None, None, None, None, None, None]

# 方法二:set去重,sorted 排序
dlist = list(sorted(set(alist), key= alist.index))
print(dlist)  # [1, 2, 3, 4, 5, 6]
# 注意: 这里用的是alist.index 而不是alist.index()
print(alist.index)  # <built-in method index of list object at 0x000001761AC92388>

if not i in blist 等价于 if i not in blist
更多用法及注意点参见 python代码if not x:if x is not None:if not x is None:使用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,783评论 0 33
  • 个人笔记,方便自己查阅使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik阅读 67,787评论 0 5
  • http://python.jobbole.com/85231/ 关于专业技能写完项目接着写写一名3年工作经验的J...
    燕京博士阅读 7,638评论 1 118
  • 时光的河入海流终於我们分头走 没有哪个港口是永远的停留 脑海之中有一个凤凰花开的路口 有我最珍惜的朋友 耳旁传来林...
    筱筱凡阅读 1,166评论 0 0
  • 第三名:处女座 可怕指数80% 可怕因素一:经常唐僧附体,一言不合就开启洗脑模式,你要是不认真听,处女就在你旁边慢...
    星座家园阅读 5,219评论 0 0