如何按顺序添加链表列表的元素?

原文标题How to add elements of list of linked list in straight order?

如何按顺序添加链表列表的元素?例如,我有链表列表:[[1, 2, 3], [4, 5, 6], [7, 8]]和列表new_list,我想按顺序添加所有元素1->2->3->...->7->8而不是按顺序1->4->7->2->5->3->6->8。对于第二种情况,我有代码:

new_list = []
        for array in lists:
            while array:
                new_list.append(array.val)
                array = array.next

但是如何修改它以获得第一种情况下的订单?

原文链接:https://stackoverflow.com//questions/71476250/how-to-add-elements-of-list-of-linked-list-in-straight-order

回复

我来回复
  • The Myth的头像
    The Myth 评论

    好的,这就是我所做的:

    lists = [[1,2,3],[4,5,6],[7,8]]
    new_list = []
    for array in lists:
        for i in array:
            new_list.append(i)
    print(new_list)
    Output: [1,2,3,4,5,6,7,8]
    

    我不知道您为什么使用array.next 或array.val,但是我认为您可以简单地获取列表并迭代它的值,然后毫无问题地附加它。

    2年前 0条评论
  • jupiterbjy的头像
    jupiterbjy 评论

    如果你想要的只是连接列表使用itertools.chain

    在此处查看官方文档。

    >>> import itertools
    >>> data = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
    >>> list(itertools.chain(*data))
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>>
    
    2年前 0条评论
  • wildgamer的头像
    wildgamer 评论

    我的想法是,我使用 pop 来获取值然后对数组进行排序,你可以试试我的想法:

    lists = [[1, 2, 3], [4, 5, 6], [7, 8]]
    new_list = []
    for array in lists:
        while array:
            new_list.append(array.pop())
    new_list.sort()

    所以你会得到你想要的结果: [1, 2, 3, 4, 5, 6, 7, 8]

    2年前 0条评论