Reputation: 41
I have these two lists
a = [(0,1), (1,2), (3,4)]
b = [[(0,1), (6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17), (3,4)]]
what i need is check if the first tuple in a exists in b then merge its reverse so expected output is
ab = [[(3,4),(1,2),(0,1),(6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17),(3,4)]]
my sample code is:
import copy
ab = copy.deepcopy(b)
for coord in b:
if a[0] in coord:
#print "Yes", coord.index(a[0])
ab.insert(coord.index(a[0]), a[::-1])
print ab
But it doesn't give me the output i want. Anybody out there who can help? thanks
Upvotes: 2
Views: 526
Reputation: 1122282
Use a list comprehension to rebuild b
:
ab = [a[:0:-1] + sub if a[0] in sub else sub for sub in b]
The a[:0:-1]
slice not only reverses a
, it also excludes the first element of a
to prevent duplicates in the output:
>>> a = [(0,1), (1,2), (3,4)]
>>> b = [[(0,1), (6,7), (8,9)], [(4,5), (7,15), (20,25)], [(18,17), (3,4)]]
>>> [a[:0:-1] + sub if a[0] in sub else sub for sub in b]
[[(3, 4), (1, 2), (0, 1), (6, 7), (8, 9)], [(4, 5), (7, 15), (20, 25)], [(18, 17), (3, 4)]]
Upvotes: 1