求两个列表的交集、并集、差集
def diff(listA, listB):
# 求交集的两种方式
retA = [i for i in listA if i in listB]
retB = list(set(listA).intersection(set(listB)))
print("retA is :", retA)
print("retB is :", retB)
# 求并集
retC = list(set(listA).union(set(listB)))
print("retC is:", retC)
# 求差集,在B中但不在A中
retD = list(set(listB).difference(set(listA)))
print("retD is:", retD)
retE = [i for i in listB if i not in listA]
print("retE is:", retE)
def main():
listA = [1, 2, 3, 4, 5]
listB = [3, 4, 5, 6, 7]
diff(listA, listB)
if __name__ == '_main_':
main()
main()
###直接上运行结果
# retA is : [3, 4, 5]
#retB is : [3, 4, 5]
#retC is: [1, 2, 3, 4, 5, 6, 7]
#retD is: [6,7]
#retE is: [6, 7]
代码思路:使用列表解析式。列表解析式一般来说比循环快,而且更python,将list转成set以后,使用set的各种方法去处理