Python 兩個列表的差集、并集和交集實現代碼
更新時間:2016年09月21日 22:26:18 投稿:mdxy-dxy
這篇文章主要介紹了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)
執(zhí)行結果:
方法二:
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)
執(zhí)行結果:
方法三:
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)
執(zhí)行結果:
注:此方法中,兩個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)
執(zhí)行結果:
注:此方法中,兩個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)
執(zhí)行結果:
注:此方法中,兩個list中的元素不能為字典
相關文章
python中split(),?os.path.split()和os.path.splitext()的用法
本文主要介紹了python中split(),?os.path.split()和os.path.splitext()的用法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02