Reputation: 21
I have a nested list like this.
[['a','g','c'],['e','c','g']...]
I am trying to see if third entry is equal to second entry in the list. If it is, I want to return first entry in that list. So since 3rd entry in list 1 is c, I want to look for c in second entry in all the list. Since list 2 has corresponding value in 2nd entry, I want to return e, then append that to nested list 1. There are multiple lists,and want to do it for all the list.
So
[['a','g','c','e']...]]
Upvotes: 1
Views: 76
Reputation: 67978
k=[['a','g','c'],['e','c','g'],['m','c','g'],['j','c','g'],['k','f','g'],['p','g','k']]
print [x+y[:1] for x,y in zip(k,k[1:]) if x[2]==y[1]]
Try this.
Upvotes: 0
Reputation: 174766
You could try the below,
>>> l = [['a','g','c'],['e','c','g']]
>>> i = l[0][2] # stores the value of 2nd index of l[0] to the variable i
>>> m = l[0] # assigns the 0th index of l to m
>>> for j in l[1:]:
if i == j[1]:
m.append(j[0])
>>> m
['a', 'g', 'c', 'e']
A complex example.
>>> l = [['a','g','c'],['e','c','g'], ['m','c','g'], ['j','c','g'], ['k','f','g'], ['p','c','g']]
>>> i = l[0][2]
>>> m = l[0]
>>> for j in l[1:]:
if i == j[1]:
m.append(j[0])
>>> m
['a', 'g', 'c', 'e', 'm', 'j', 'p']
Upvotes: 2