删除列表中的重复元素并且保持顺序不变,可散列表与不可散列表

删除列表中的重复元素并且保持顺序不变,可散列表与不可散列表

  • 可散列表
def dedupe(items):
    seen = set()
    for item in items:
        if item not in seen:
            yield item
            seen.add(item)

if __name__ == '__main__':
    a = [5,5,2,1,9,1,5,10]
    print(a)
    print(list(dedupe(a)))
  • 不可散列表
def buha(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)

if __name__ == '__main__':
    a = [
        {'x':2,'y':3},
        {'x':1,'y':4},
        {'x':2,'y':3},
        {'x':2,'y':3},
        {'x':10,'y':15}
    ]
    print(a)
    print(list(buha(a,key=lambda a:(a['x'],a['y']))))

你可能感兴趣的:(Python)