javascript 版
/*JS删除数组对象中的重复元素并保持顺序不变,*/
function* arraySet(items, key=null) {
let s = new Set();
for (let item of items) {
let value = key ? key(item) : item;
!s.has(value) && (yield item, s.add(value))
}
}
var ret = arraySet([
{a: 1, b: 2},
{a: 1, b: 2},
{a: 3, b: 2},
{a: 4, b: 2},
{a: 3, b: 2},
{a: 1, b: 2},
], item=> [item['a'], item['b']].join(''));
console.log(...ret);
// [ { a: 1, b: 2 }, { a: 3, b: 2 }, { a: 4, b: 2 } ]
python 版
# 删除列表中的重复元素并保持顺序不变, 列表元素为散列类型"""
def listSet(items, key=None):
s = set()
for item in items:
val = item if key is None else key(item)
if val not in s:
yield item
s.add(val)
arr1 = [
{'x': 1, 'y': 3},
{'x': 3, 'y': 3},
{'x': 2, 'y': 3},
{'x': 1, 'y': 3},
{'x': 2, 'y': 3}
]
print(list(listSet(arr1, key=lambda item: (item['x'], item['y']))))
# [{'x': 1, 'y': 3}, {'x': 3, 'y': 3}, {'x': 2, 'y': 3}]