熱線電話:13121318867

登錄
首頁精彩閱讀Python 兩個列表的差集、并集和交集實現代碼
Python 兩個列表的差集、并集和交集實現代碼
2017-11-23
收藏

Python 兩個列表的差集、并集和交集實現代碼

這篇文章主要介紹了Python 兩個列表的差集、并集和交集實現代碼,需要的朋友可以參考下

①差集
方法一:    
if __name__ == '__main__':
    a_list = [{'a' : 1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}]
    b_list = [{'a' : 1}, {'b' : 2}]
    ret_list = []
    for item in a_list:
        if item not in b_list:
            ret_list.append(item)
    for item in b_list:
        if item not in a_list:
            ret_list.append(item)
    print(ret_list)

執行結果:

方法二:
    
if __name__ == '__main__':
    a_list = [{'a' : 1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}]
    b_list = [{'a' : 1}, {'b' : 2}]
    ret_list = [item for item in a_list if item not in b_list] + [item for item in b_list if item not in a_list]
    print(ret_list)

執行結果:

方法三:
    
if __name__ == '__main__':
    a_list = [1, 2, 3, 4, 5]
    b_list = [1, 4, 5]
    ret_list = list(set(a_list)^set(b_list))
    print(ret_list)

執行結果:

注:此方法中,兩個list中的元素不能為字典

②并集
    
if __name__ == '__main__':
    a_list = [1, 2, 3, 4, 5]
    b_list = [1, 4, 5]
    ret_list = list(set(a_list).union(set(b_list)))
    print(ret_list)

執行結果:
注:此方法中,兩個list中的元素不能為字典

③交集
    
if __name__ == '__main__':
    a_list = [1, 2, 3, 4, 5]
    b_list = [1, 4, 5]
    ret_list = list((set(a_list).union(set(b_list)))^(set(a_list)^set(b_list)))
    print(ret_list)

執行結果:

注:此方法中,兩個list中的元素不能為字典


數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢