如何从列表中删除重复项,同时保持顺序?使用集合删除重复项会破坏原始顺序。 是否有内置的或python的习语?
当前回答
你可以做一个丑陋的列表理解黑客。
[l[i] for i in range(len(l)) if l.index(l[i]) == i]
其他回答
Pandas用户应该查看Pandas .unique。
>>> import pandas as pd
>>> lst = [1, 2, 1, 3, 3, 2, 4]
>>> pd.unique(lst)
array([1, 2, 3, 4])
该函数返回一个NumPy数组。如果需要,可以使用tolist方法将其转换为列表。
x = [1, 2, 1, 3, 1, 4]
# brute force method
arr = []
for i in x:
if not i in arr:
arr.insert(x[i],i)
# recursive method
tmp = []
def remove_duplicates(j=0):
if j < len(x):
if not x[j] in tmp:
tmp.append(x[j])
i = j+1
remove_duplicates(i)
remove_duplicates()
消除序列中的重复值,但保留其余项的顺序。使用通用发电机功能。
# for hashable sequence
def remove_duplicates(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
a = [1, 5, 2, 1, 9, 1, 5, 10]
list(remove_duplicates(a))
# [1, 5, 2, 9, 10]
# for unhashable sequence
def remove_duplicates(items, key=None):
seen = set()
for item in items:
val = item if key is None else key(item)
if val not in seen:
yield item
seen.add(val)
a = [ {'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 1, 'y': 2}, {'x': 2, 'y': 4}]
list(remove_duplicates(a, key=lambda d: (d['x'],d['y'])))
# [{'x': 1, 'y': 2}, {'x': 1, 'y': 3}, {'x': 2, 'y': 4}]
MizardX的答案提供了多种方法的良好集合。
这是我自言自语时想到的:
mylist = [x for i,x in enumerate(mylist) if x not in mylist[i+1:]]
使用_sorted_ a numpy数组的相对有效方法:
b = np.array([1,3,3, 8, 12, 12,12])
numpy.hstack([b[0], [x[0] for x in zip(b[1:], b[:-1]) if x[0]!=x[1]]])
输出:
array([ 1, 3, 8, 12])
推荐文章
- 试图在Windows 10上运行Python时出现“权限被拒绝”
- 如何在Django中设置时区
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- defaultdict的嵌套defaultdict
- 构造tkinter应用程序的最佳方法?
- 如何在Python中逐行打印字典?
- 当试图运行Python脚本时,“ImportError:没有命名模块”
- pylab和pyplot的区别是什么?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- Argparse:确定使用了哪个子解析器
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- c#对象列表,我如何得到一个属性的和
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?