一、list基本操作 list = [1, 2, 3] list.append(5) print(list) list.extend([6, 7]) # extend是将可迭代对象的元素依次加入列表 print(list) list.append([6, 7]) # append是把传入的参数当成一个元素加入列表 print(list) list.reverse() # 元素翻转,注意不能将这个操作赋给一个变量,此操作是...
1. 获取两个list 的交集 #方法一: a=[2,3,4,5] b=[2,5,8] tmp = [val for val in a if val in b] #列表推导式求的两个列表的交集 print tmp #[2, 5] #方法二 print list(set(a).intersection(set(b))) #列用集合的取交集方法 2. 获取两个list 的并集 print list(s...
2.将list转成set以后,使用set的各种方法去处理。
求集合 A 与集合 B 的交集lst_a = [1,2,3,4,5] lst_b = [3,4,5,6,7] set_a = set(lst_a) set_b = set(lst_b) set_c = set_a.intersection(lst_b) print(list(set_c)) 运行结果:[3, 4, 5]求集合 A 与集合 B 的并集lst_a = [1,2,3,4,5] lst_b = [3,4,5,6,7]...
1)求多个list的交集: #list(set(list1).intersection(set(list2),set(list3),...))#如果有很多个,可以继续添加res=list(set(list1).intersection(list2,list3,...))#如果有很多个,可以继续添加 1. 2. 结果应该是:res = [2,4] 2)求多个list的并集: #list...
x & y # 交集 x | y # 并集 x - y # 差集 set([1,2,3])|set([4,7,8]) Out[55]: {1, 2, 3, 4, 7, 8} set([1,2,3])|set([2,4,7,8]) Out[56]: {1, 2, 3, 4, 7, 8} len(set([1,2,3])|set([2,4,7,8])) Out[57]: 6 list(set([1,2,3])|set([2...
在这个示例中,我们有两个包含字符串的集合,并且可以使用集合运算来查找它们的交集和并集。列表集合:list1 = [1, 2, 3, 4, 5]list2 = [3, 4, 5, 6, 7]set1 = set(list1)set2 = set(list2)difference_result = set1.difference(set2)print(difference_result) # 输出: {1, 2} 在这个示例...
获取两个list 的交集: 代码语言:javascript 复制 #方法一:a=[2,3,4,5]b=[2,5,8]tmp=[valforvalinaifvalinb]print(tmp)#[2,5]#方法二 比方法一快很多! printlist(set(a).intersection(set(b))) 获取两个list 的并集: 代码语言:javascript ...
在python3对列表的处理中,会经常使用到Python求两个list的差集、交集与并集的方法。 一.两个list差集 如有下面两个数组: a = [1,2,3] b = [2,3] 想要的结果是[1] 下面记录一下三种实现方式: 1. 正常的方式 ret = [] foriina: ifinotinb: ...
2、并集 >>> list(set(t).union(set(s))) [1, 2, 3, 4, 5, 6] 3、交集 >>> list(set(t).intersection(set(s))) [4] 哈哈,以上就是python小工具关于list的交集,并集,差集的介绍。有兴趣欢迎关注:python小工具。一起学习pyhton和pandas发布...