Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting elements from list according to their labels in the other list

Tags:

python

list

I have two lists Lx and Ly, each element from Lx has a corresponding label in Ly. Example:

Lx = [[1,2,5], [5,2,7], [7,0,4], [9,2,0], [1,8,5], [3,4,5], [3,2,7], [2,9,7]]
Ly = [A, C, A, B, A, B, C, C]

How can easily I get a list/label where elements of a list are the elements from Lx that have the same label in Ly ? That is:

[[1,2,5], [7,0,4], [1,8,5]]
[[5,2,7], [3,2,7], [2,9,7]]
[[9,2,0], [3,4,5]]
like image 537
shn Avatar asked Mar 01 '13 12:03

shn


1 Answers

Lx = [[1,2,5], [5,2,7], [7,0,4], [9,2,0], [1,8,5], [3,4,5], [3,2,7], [2,9,7]]
Ly = ['A', 'C', 'A', 'B', 'A', 'B', 'C', 'C']
d = {}
for x,y in zip(Lx,Ly):
    d.setdefault(y, []).append(x)

d is now:

{'A': [[1, 2, 5], [7, 0, 4], [1, 8, 5]],
 'B': [[9, 2, 0], [3, 4, 5]],
 'C': [[5, 2, 7], [3, 2, 7], [2, 9, 7]]}
like image 79
eumiro Avatar answered Oct 19 '22 11:10

eumiro