Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: intersection of nested lists where order matters

I would like to find the intersection between nested lists while maintaining the order.

taxa = [['E_pyrifoliae_Ep1_96', 'Bacteria', 'Proteobacteria', 'Gammaproteobacteria', 'Enterobacteriales', 'Enterobacteriaceae', 'Erwinia'],
 ['E_amylovora_CFBP1430', 'Bacteria', 'Proteobacteria', 'Gammaproteobacteria', 'Enterobacteriales', 'Enterobacteriaceae', 'Erwinia'], 
 ['E_amylovora_ATCC49946', 'Bacteria', 'Proteobacteria', 'Gammaproteobacteria', 'Enterobacteriales', 'Enterobacteriaceae', 'Erwinia']]

To find the intersection I have:

set.intersection(*map(set, taxa))

or

set(taxa[0]).intersection(*taxa)

but the original order is not kept.

set(['Erwinia', 'Gammaproteobacteria', 'Enterobacteriaceae', 'Enterobacteriales', 'Proteobacteria', 'Bacteria'])

Basically, what I need to do is find the last common element between the nested lists (they are taxanomic classifications ). So I don't need to find all the intersections, just the last one or all of them when I can just call on the last entry.

intersection_lst[-1]

In this instance I want the output to be 'Erwinia'.

Thanks for your help.

like image 736
Binnie Avatar asked Aug 14 '12 16:08

Binnie


People also ask

How do you find the intersection of three lists in Python?

Step1: input the elements of three lists. Step2: Use intersection method, first convert lists to sets then apply intersection method of two sets and find out common elements then this set intersect with the third set.

How do nested lists work?

A nested list is a list that appears as an element in another list. In this list, the element with index 3 is a nested list. If we print( nested[3] ), we get [10, 20] .


1 Answers

Find the intersection, then reimpose order.

intersection_set = set.intersection(*map(set, taxa))
intersection_lst = [t for t in taxa[0] if t in intersection_set]

Or, if you are inordinately fond on one-liners:

sorted(set.intersection(*map(set, taxa)), key=lambda x: taxa[0].index(x))
like image 68
Steven Rumbalski Avatar answered Sep 22 '22 13:09

Steven Rumbalski