Excluding common element from list python [duplicate] - python

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python, compute list difference
I have two lists
For example:
A = [1,3,5,7]
B = [1,2,3,4,5,6,7,8]
Now, A is always a subset of B
I want to generate a third list C:
which has elements which are present in B but absent in A
like
C = [2,4..]
Thanks

List comprehensions are one way to do this:
[x for x in B if x not in A]
If you use Python, I recommend gaining familiarity with list comprehensions. They're a very powerful tool.
(Several people have suggested using set. While this is a very good idea if you only care about whether or not an element is in the set, note that it will not preserve the order of the elements; a list comprehension will.)

>>> set(B) - set(A)
set([8, 2, 4, 6])
or
>>> sorted(set(B) - set(A))
[2, 4, 6, 8]

An easy way to do this is
C = [x for x in B if x not in A]
This will become slow for big lists, so it would be better to use a set for A:
A = set(A)
C = [x for x in B if x not in A]
If you have multiple operations like this, using sets all the time might be the best option. If A and B are sets, you can simply do
C = B - A

C = sorted(list(set(B) - set(A)))
That should do it.

Related

Is there a brief way to Get the indices of all elements from list A in list B [duplicate]

This question already has answers here:
Find indexes of common items in two python lists
(3 answers)
Closed 1 year ago.
Assume we have two lists, A and B. Is there a way to get the indices of elements in the list B, which are in the list A?
For example:
A = [1,2,3,4]
B = [3,4,1,2,5]
The result should be:
[2,3,0,1]
Could it be implemented without for-loop (or fast)?
This should work for your use case:
result = [A.index(x) for x in B if x in A]
Use index function
A = [1,2,3,4]
B = [3,4,1,2,5]
lst=[]
for i in A:
res=B.index(i)
lst.append(res)
print(lst)
# [2, 3, 0, 1]

Python - Obtain indices of intersecting values in two arrays [duplicate]

This question already has answers here:
Finding indices of matches of one array in another array
(4 answers)
Closed 2 years ago.
If I have two arrays:
A=[1,2,3,4,5,6,7]
B=[2,4,7]
I would like to obtain an array C that contains the indices of the the values of B also found in A
C=[1,3,6]
I'm quite new to Python and I'm frustrated of not being able to find an elegant solution to such a simple task without the need of using a loop combined with numpy.where().
Thanks in advance!!
Here's a linear-time solution: to efficiently test whether an element is in B, convert it to a set first.
B_set = set(B)
C = [i for i, x in enumerate(A) if x in B_set]
For large inputs, this is better than using .index in a loop, since that requires repeatedly searching the list in O(mn) time, where m and n are the size of A and B. In comparison, the solution above takes O(m + n) time to convert to a set and then build the result list.
You can use np.isin and np.nonzero.
a=np.array([1,2,3,4,5,6,7])
b=np.array([2,4,7])
c=np.nonzero(np.isin(a,b))[0]
# array([1, 3, 6], dtype=int64)
There is a special function in the numpy module for this, intersect1d by passing True in its return_indices argument you get indices of the intersection.
import numpy as np
a = np.array([1,2,3,4,5,6,7])
b = np.array([2,4,7])
c = np.intersect1d(a, b, return_indices=True)[1]
# array([1, 3, 6], dtype=int64)
You can iterate over B and use index() on A with the values
c = [A.index(i) for i in B]
As per of #kaya3's comment you can add a check if the value of B present in A in case it can contain non existing values
c = [A.index(i) for i in B if i in A]
You can use the index function.
A = [1,2,3,4,5,6,7]
B = [2,4,7]
C = [a.index(b) for b in B]
C = list(map(lambda b: a.index(b),B)

Python: how to find common values in three lists

I try to find common list of values for three different lists:
a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]
of course naturally I try to use the and operator however that way I just get the value of last list in expression:
>> a and b and c
out: [3,4,5,6]
Is any short way to find the common values list:
[3,4]
Br
Use sets:
>>> a = [1, 2, 3, 4]
>>> b = [2, 3, 4, 5]
>>> c = [3, 4, 5, 6]
>>> set(a) & set(b) & set(c)
{3, 4}
Or as Jon suggested:
>>> set(a).intersection(b, c)
{3, 4}
Using sets has the benefit that you don’t need to repeatedly iterate the original lists. Each list is iterated once to create the sets, and then the sets are intersected.
The naive way to solve this using a filtered list comprehension as Geotob did will iterate lists b and c for each element of a, so for longer list, this will be a lot less efficient.
out = [x for x in a if x in b and x in c]
is a quick and simple solution. This constructs a list out with entries from a, if those entries are in b and c.
For larger lists, you want to look at the answer provided by #poke
For those still stumbling uppon this question, with numpy one can use:
np.intersect1d(array1, array2)
This works with lists as well as numpy arrays.
It could be extended to more arrays with the help of functools.reduce, or it can simply be repeated for several arrays.
from functools import reduce
reduce(np.intersect1d, (array1, array2, array3))
or
new_array = np.intersect1d(array1, array2)
np.intersect1d(new_array, array3)

Intersection in Python List

I'm newbie on Python. I have this list:
a = [[0,1,2,3],[4,5,6,7,8,9], ...]
b = [[0,6,9],[1,5], ...]
a & b can have more components, depends on data. I want to know is there any intersection on these lists? If there's any intersection, I wanna have a result like this:
c = [[6,9], ...]
The set type, built into Python, supports intersection natively. However, note that set can only hold one of each element (like a mathematical set). If you want to hold more than one of each element, try collections.Counter.
You can make sets using {} notation (like dictionaries, but without values):
>>> a = {1, 2, 3, 4, 5}
>>> b = {2, 4, 6, 8, 10}
and you can intersect them using the & operator:
>>> print a & b
set([2, 4])
Given that intersection is an operation between two sets, and you have given two lists of lists, it's very unclear what you're looking for. Do you want the intersection of a[1] and b[0]? Do you want the intersection of every possible combination?
I'm guessing you want the intersection of every combination of two sets between your two lists, which would be:
from itertools import product
[set(x).intersection(set(y)) for x, y in product(a, b)]
First of all, in your example code this is not a tuple, it's a list (the original question asked about lists, but references tuples in the example code).
To get an intersection of two tuples or lists, use a code like this:
set((1,2,3,4,5)).intersection(set((1,2,3,7,8)))
In one line:
common_set = set([e for r in a for e in r])&set([e for r in b for e in r])
Or easier:
common_set = set(sum(a,[])) & set(sum(b,[]))
Common will be a set. You can easily convert set to the list is you need it:
common_list = list(common_set)
Another way to do it... assuming you want the intersection of the flatten list.
>>> from itertools import chain
>>> a = [[0,1,2,3],[4,5,6,7,8,9]]
>>> b = [[0,6,9],[1,5]]
>>> list(set(chain(*a)).intersection(set(chain(*b))))
[0, 9, 5, 6, 1]

Simplest way to check if multiple items are (or are not) in a list? [duplicate]

This question already has answers here:
How to check if one of the following items is in a list?
(14 answers)
Closed 8 years ago.
I want to use syntax similar to this:
if a in b
but I want to check for more than one item, so I need somthing like this:
if ('d' or 'g' or 'u') in a
but I know it doesn't work.
so I did it this way:
for i in a:
for j in ['d','g','u']:
if i==j
and it worked,
but I wonder if there's a simpler way.
any and all can be used to check multiple boolean expressions.
a = [1, 2, 3, 4, 5]
b = [1, 2, 4]
print(all(i in a for i in b)) # Checks if all items are in the list
print(any(i in a for i in b)) # Checks if any item is in the list
Use any plus a generator:
if any(x in d for x in [a, b, c]):
Or check for set intersection:
if {a, b, c} & set(d):

Categories

Resources