企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
>[success] # 对list 元素去重 >[danger] ##### set -- 去重,但元素位置被打乱 ~~~ l = ["a", "c", "b", "e", "a"] print(set(l)) 打印结果: {'e', 'c', 'b', 'a'} ~~~ >[danger] ##### 只针对哈希去重,顺序不变 * 哈希就是内部有一个__hash__方法,在声明周期不可变的,例如数字,字符串,元组 ~~~ l = ["a", "c", "b", "e", "a"] def dedupe(items): seen =set() for i in items: if i not in seen: yield i seen.add(i) print(list(dedupe(l))) 打印结果: ['a', 'c', 'b', 'e'] ~~~ >[danger] ##### 针对哈希值的字典 * 字典中 v 是变化的可以重新不断的赋值 ~~~ def dedupe(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) print(list(dedupe(d,lambda d:(d["x"],)))) 打印结果: [{'y': 2, 'x': 1}, {'y': 4, 'x': 3}] ~~~ ![](https://box.kancloud.cn/a6be9d59c8144d84767d1854d09abbe5_800x256.png)