# !/usr/bin/env python
# -*- coding:utf-8 -*-
'''給定一個(gè)列表掘譬,去重,并保證元素的原始次序不變'''
alist = [1, 1, 1, 1, 2, 3, 4, 4, 4, 5, 6, 1, 2, 2]
# 方法一:列表推導(dǎo)式
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 等價(jià)于 if i not in blist
更多用法及注意點(diǎn)參見 python代碼if not x:
和if x is not None:
和if not x is None:
使用