So I have lists of numbers, and I would like to find numbers that exist in all the lists. I prefer not to use loop if possible.
Here is one example
a = [1, 2, 3, 4]
b = [2, 3, 4, 5, 6]
c = [3, 4, 5, 6, 10, 12]
df['A'] = [a, b, c]
The output is expected to be
[3, 4]
My problem here is, the number of lists is not given and not fixed. It can be about 20 lists with different lengths (e.g. [a, b, c, d, e, g, ..., l])
I have seen answers using set(a) & set(b) & set(c), but I am not sure how to apply this in my case.
You could use map
along with set.intersection
:
>>> a = [1, 2, 3, 4]
>>> b = [2, 3, 4, 5, 6]
>>> c = [3, 4, 5, 6, 10, 12]
>>> elements_in_all = list(set.intersection(*map(set, [a, b, c])))
>>> elements_in_all
[3, 4]
I'm not sure why you'd want to avoid loops, since that's .. really what you're asking for - looping over a list of lists and keeping the set of unique values.
l = [a, b, c]
s = None
for e in l:
if not s:
s = set(e)
else:
s &= set(e)
s => set([3, 4])
You can also create a functional version that doesn't explicitly use loops, and still support an arbitrary number of arguments:
reduce((lambda x,y: x & y), map(set, l))
First, convert every list in your containing list l
to a set, then use reduce to apply the intersection for each element contained - the result is a single set with the elements common to all lists.
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