合并两个列表,如果第一个列表的最后一个元素是第二个列表的第一个元素



我正在尝试合并两个列表,以防第二个元素等于下一个列表的第一个元素。

我有以下列表:

a = [[1, 2], [4, 6], [3, 4]]

我所做的第一件事是对列表进行排序,以便能够比较元素:

sort_a = sorted(a, key = lambda pos: pos[0])

给我作为输出:

[[1, 2], [3, 4], [4, 6]]

现在我正在努力比较元素。我的理由如下:

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

期望输出是[[1,2],[3,6]]

因为你想用ii+1索引列表,i必须最多是列表的长度减去2。另一个问题是,您希望在遍历列表时更改列表,这可能会弄乱索引号。您可以通过反向迭代索引来避免这个问题,这样当您删除一个项时,那些尚未处理的项的索引不会改变。

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]]