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)  # 

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

你可能感兴趣的:(python列表去重不改原序的两种pythonic方法)