【问题标题】:Merge two list if the last element of the first list is the first of the second如果第一个列表的最后一个元素是第二个列表的第一个,则合并两个列表
【发布时间】:2021-11-27 11:02:19
【问题描述】:

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

我有以下列表:

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

【问题讨论】:

  • 你的问题到底是什么?
  • 你的意思可能是[i][1] == [i+1][0]
  • 我的问题是如果两个列表具有相同的值,我想合并它们。我的推理产生了一个超出范围的错误

标签: python list merge


【解决方案1】:

由于您想用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]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多