# !/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:
使用
网友评论