I'm trying to write a piece of code that can automatically factor an expression. For example, if I have two lists [1,2,3,4] and [2,3,5], the code should be able to find the common elements in the two lists, [2,3], and combine the rest of the elements together in a new list, being [1,4,5].
From this post: How to find list intersection? I see that the common elements can be found by
set([1,2,3,4]&set([2,3,5]).
Is there an easy way to retrieve non-common elements from each list, in my example being [1,4] and [5]?
I can go ahead and do a for loop:
lists = [[1,2,3,4],[2,3,5]] conCommon = [] common = [2,3] for elem in lists: for elem in eachList: if elem not in common: nonCommon += elem
But this seems redundant and inefficient. Does Python provide any handy function that can do that? Thanks in advance!!
The most efficient and recommended method to perform this task is using the combination of set() and map() to achieve it. Firstly converting inner lists to tuples using map, and outer lists to set, use of ^ operator can perform the set symmetric difference and hence perform this task.
You can use the . __xor__ attribute method.
Method 1:Using Set's & property Convert the lists to sets and then print set1&set2. set1&set2 returns the common elements set, where set1 is the list1 and set2 is the list2. Below is the Python3 implementation of the above approach: Python3.
Using Python's import numpy, the unique elements in the array are also obtained. In the first step convert the list to x=numpy. array(list) and then use numpy. unique(x) function to get the unique values from the list.
Use the symmetric difference operator for set
s (aka the XOR operator):
>>> set([1,2,3]) ^ set([3,4,5]) set([1, 2, 4, 5])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With