利用python中集合操作尋找相同點(diǎn)以及重復(fù)項(xiàng)

  1. 找出字典中的相同與不同
# -*- coding: utf-8 -*-
# @Time    : 2024/7/17 下午8:57
# @Author  : s
a = {
    'x': 1,
    'y': 2,
    'z': 3
}
b = {
    'w': 10,
    'x': 11,
    'y': 2
}
# 找a,b 相同的key
common_key = a.keys() & b.keys()
# 找在a不在b
diff_akey = a.keys() - b.keys()
# 找a,b相同的key,value
common_k_v = a.items() & b.items()
print(common_key)
print(diff_akey)
print(common_k_v)
  1. 從序列中移除重復(fù)項(xiàng)并保持元素間的順序
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2024/7/17 下午9:41
# @Author  : s


def dedupe(items):
    """可哈希"""
    seen = set()
    for item in items:
        if item not in seen:
            yield item
            seen.add(item)


def dedupe2(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__':
    a1 = [1, 5, 2, 1, 9, 1, 5, 10]
    print(list(dedupe(a1)))
    a2 = [{'x': 1, 'y': 2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}]
    print(list(dedupe2(a2, key=lambda d: (d['x'],d['y']))))
    print(list(dedupe2(a2, key=lambda d: d['x'])))

如果只是去除重復(fù)項(xiàng),并不關(guān)心元素間的順序,最簡(jiǎn)單的方法:set([1,2,3,2,3,5]) 結(jié)果為:{1,2,3,5}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容