# 删除重复元素，保持顺序不变

1数组去重

代码：

```python
def dedupe(items):
    seen=set()
    for item in items:
        if item not in seen:
            yield item
            seen.add(item)
a=[5,5,2,1,9,1,5,10]
print(a)
print(list(dedupe(a)))
```

结果：

```
[5, 5, 2, 1, 9, 1, 5, 10]
[5, 2, 1, 9, 10]
```

## 以上只能对散列元素才能之么做，在对象序列中去除重复项，保持顺序不变？

```python
def buha(items,key=None):
    seen=set()
    for item in items:
#         print(seen)
        val=item if key is None else key(item)
        print(val)
        if val not in seen:
            yield item
            seen.add(val)
a=[{'x':2,'y':3},{'x':1,'y':4},
      {'x':2,'y':3},{'x':10,'y':15}]
print(a)
print(list(buha(a,key=lambda x:(x['x'],x['y']))))
```

```
[{'x': 2, 'y': 3}, {'x': 1, 'y': 4}, {'x': 2, 'y': 3}, {'x': 10, 'y': 15}]
(2, 3)
(1, 4)
(2, 3)
(10, 15)
[{'x': 2, 'y': 3}, {'x': 1, 'y': 4}, {'x': 10, 'y': 15}]
```

## 自定义

```python
class Foo:
    def __init__(self, name, count):
        self.name = name
        self.count = count

    def __hash__(self):
        # 当两个变量的哈希值不相同时，就认为这两个变量是不同的。
        print("%s调用了哈希方法" % self.name)
        return hash(self.count)

    def __eq__(self, other):
        # 当两个变量哈希值一样时，调用__eq__方法，比较是否具有相同的各种属性，可以简单地理解为值是否相等
        # self是存在的一方对象，other是新来的和存在的冲突的对象
        print("%s调用了eq方法" % self.name)
        if self.count == other.count:
#         if self.__dict__ == other.__dict__:
            return True
        else:
            return False

    def __repr__(self, ):
        return 'print:%s' % (self.name)


f1 = Foo('f1', 1)
f2 = Foo('f2', 2)
f3 = Foo('f3', 3)
f4 = Foo('f4', 3)
f5 = Foo('f5', 3)
f6 = Foo('f6', 3)
ms = [f1, f2, f3, f4, f5,f6]
print(set(ms))
```

```
f1调用了哈希方法
f2调用了哈希方法
f3调用了哈希方法
f4调用了哈希方法
f3调用了eq方法
f5调用了哈希方法
f3调用了eq方法
f6调用了哈希方法
f3调用了eq方法
{print:f1, print:f2, print:f3}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://im-qianuxn.gitbook.io/pytorch/ji-suan-ji/python/2.1.2-shan-chu-zhong-fu-yuan-su-bao-chi-shun-xu-bu-bian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
