views:

95

answers:

2

Hello everybody,

I have two nested lists of different sizes:

A = [[1, 7, 3, 5], [5, 5, 14, 10]]

B = [[1, 17, 3, 5], [1487, 34, 14, 74], [1487, 34, 3, 87], [141, 25, 14, 10]]

I'd like to gather all nested lists from list B if A[2:4] == B[2:4] and put it into list L:

L = [[1, 17, 3, 5], [141, 25, 14, 10]]

Additionally if the match occurs then I want to change last element of sublist B into first element of sublist A so the final solution would look like this:

L1 = [[1, 17, 3, 1], [141, 25, 14, 5]]
+3  A: 

It looks like this does what you want:

> [b for b in B if b[2:4] in [a[2:4] for a in A]]
[[1, 17, 3, 5], [141, 25, 14, 10]]

But, for efficiency's sake, you may want to precompute the slices of A.

> a_slices = [a[2:4] for a in A]
> [b for b in B if b[2:4] in a_slices]
[[1, 17, 3, 5], [141, 25, 14, 10]]

Here's something that looks like it meets your new requirements:

> [b[:-1] + a[:1] for b in B for a in A if b[2:4] == a[2:4]]
[[1, 17, 3, 1], [141, 25, 14, 5]]
Stephen
The second version almost reads like english. Pretty sweet.
zildjohn01
Great help!! Thank you. I'm almost there. I added one more piece of information that I'd like to include in the code.
@elfuego1 : Edited to show.
Stephen
Thank you VERY much Stephen!!! You heleped me a LOT ;-)
+1  A: 
[x for x in B if any(x[2:4] == y[2:4] for y in A)]
Ignacio Vazquez-Abrams