I am trying to merge two lists in case the second element is equal to the first one of the next list.
I have the following list of lists:
a = [[1, 2], [4, 6], [3, 4]]
The first thing I have done is to sort the list so that I will be able to compare the elements:
sort_a = sorted(a, key = lambda pos: pos[0])
Which give me as output:
[[1, 2], [3, 4], [4, 6]]
Now I am struggling in comparing the elements. My reasoning would be the following:
for i, j in sort_a:
# Compare the elements from the lists I am interested in merging
# If there is a match, the two lists would be merged
if sort_a[i][1] == sort_a[i 1][0]:
# The code goes here
else:
return sort_a[i][j] # Else it would keep the original list
So the expected output would be [[1,2],[3,6]]
.
CodePudding user response:
Since you want to index the list with i
and i 1
, i
must at most be the length of the list minus 2. Another problem is that you want to change the list while iterating over it, which can for example mess up the index numbers. You can avoid that problem here by iterating over the indices in reverse, so that when you delete an item, the indices of those items that are yet to be processed do not change.
result = sort_a.copy()
for i in reversed(range(len(sort_a) - 1)):
if sort_a[i][1] == sort_a[i 1][0]:
result[i][1] = result[i 1][1]
del result[i 1]
print(result)
[[1, 2], [3, 6]]