Python: Merging lists with lists
I have a list:
packets=[['B', 'A'], ['B', 'C'], ['A', 'D'], ['C', 'D'], ['C', 'E'], ['D', 'E'], []]
I have two for loops on the same list something like:
for a in packets[:]:
for b in packets[:]:
i.e., each time a=['B','A']
b
iterates from ['B','A']
all the way to ['D','E']
. This is what I want to do:
If the last element of a
is equal to the first element of b
i.e., when a=['B','A']
and b=['A','D']
I must have ['B','A','D']
. Again the last element of ['B','A'开发者_StackOverflow,'D']
is equal to the first element of ['D','E']
. So, now I must have ['B','C','D','E']
.
Similarly, when A=['B','C']
and b=['C','E']
I must have ['B','C','E']
. When A=['B','C']
and b=['C','D']
and b=['D','E']
I must have ['B','C','D','E']
and so on.
Any ideas?
Not sure if this is what you want, but
>>> packets=[['B', 'A'], ['B', 'C'], ['A', 'D'], ['C', 'D'], ['C', 'E'], ['D', 'E'], []]
>>>
>>> for a in packets:
... for b in packets:
... if a and b and a[-1]==b[0]:
... print a[:-1]+b
... packets.append(a[:-1]+b)
...
['B', 'A', 'D']
['B', 'C', 'D']
['B', 'C', 'E']
['A', 'D', 'E']
['C', 'D', 'E']
['B', 'A', 'D', 'E']
['B', 'C', 'D', 'E']
精彩评论