cookbook 1.10
对序列中移除重复项且保持元素间顺序不变
问题描述:
去掉重复元素,但其中的原始顺序不变
一、可哈希的序列
可哈希:在生存期期间不变,有__hash__方法
如整型,字符串,元组,浮点数
def dequpe(items):
seen = list()
for i in items:
if i not in seen:
yield i
seen.append(i)
# 列表可以实现
a =
print(list(dequpe(a)))
二、不可哈希或比较复杂的数据结构
def dequpe_plus(items, key=None):
seen = list()
for i in items:
val = i if key is None else key(i)
if val not in seen:
yield i
seen.append(val)
b = [{"a": 1, "b": 2}, {"a": 2, "b": 1}, {
"a": 1, "b": 2}, {"a": 3, "b": 3}, {"a": 1, "b": 4}]
print(list(dequpe_plus(b, key=lambda d: (d["a"], d["b"]))))# a,b值不重复
print(list(dequpe_plus(b, key=lambda d: d["a"])))# a的值不重复
[{'a': 1, 'b': 2}, {'a': 2, 'b': 1}, {'a': 3, 'b': 3}, {'a': 1, 'b': 4}]
[{'a': 1, 'b': 2}, {'a': 2, 'b': 1}, {'a': 3, 'b': 3}]
页:
[1]