In Python, finding the intersection, union and difference of two lists is a frequently encountered requirement, and it is relatively simple.
The easiest thing to think of is to write a loop, loop through the two lists separately, and then determine whether the element is in the other list, and get the final result.
But this method is relatively low and has no technical content. As a Python programmer, you must write enough pythonic code.
Not much nonsense, just look at the code.
# list_operate.py
def main():
list_a =[1,2,3,4,5]
list_b =[4,5,6,7,8]
# Two ways to find intersection
res_a =[i for i in list_a if i in list_b]
res_b =list(set(list_a).intersection(set(list_b)))print(f"res_a is: {res_a}")print(f"res_b is: {res_b}")
# Find the union
res_c =list(set(list_a).union(set(list_b)))print(f"res_c is: {res_c}")
# Two ways to find the difference set, in B but not in A
res_d =[i for i in list_b if i not in list_a]
res_e =list(set(list_b).difference(set(list_a)))print(f"res_d is: {res_d}")print(f"res_e is: {res_e}")if __name__ =='__main__':main()
Take a look at the output:
# python3 list_operate.py
res_a is:[4,5]
res_b is:[4,5]
res_c is:[1,2,3,4,5,6,7,8]
res_d is:[6,7,8]
res_e is:[8,6,7]
The result is still okay. Don't operate like a tiger. If the result is wrong, it will be embarrassing.
To sum up, there are basically two ideas:
the above.
Follow the official account AlwaysBeta to learn more pythonic tips.