对列表列表进行排序,使列表的最后一个元素等于下一个列表的第一个元素

时间:2018-04-14 13:42:57

标签: python

我有一个列表

my_list=[[9, 10, 1], [1, 7, 5, 6, 11], [0, 4], [4, 2, 9]]

我想对此列表进行排序,使其看起来像这样:

result=[[0, 4], [4, 2, 9],[9, 10, 1], [1, 7, 5, 6, 11]]

条件是: 1.列表应以包含零的元素开头。 2.列表的最后一个元素应该与下一个列表的第一个元素相同,依此类推。 3.子列表中的元素应与原始列表的顺序相同。

谢谢。

4 个答案:

答案 0 :(得分:1)

快速解决方案是构建一个dict,根据第一个元素将数字映射到子列表:

dct = {sublist[0]: sublist for sublist in my_list}
# {0: [0, 4], 9: [9, 10, 1], 1: [1, 7, 5, 6, 11], 4: [4, 2, 9]}

然后,从数字0开始,查找需要在dict中添加的下一个子列表:

result = []
num = 0  # start with the sublist where the first element is 0
while True:
    try:
        # find the sublist that has `num` as the first element
        sublist = dct[num]
    except KeyError:
        # if there is no such sublist, we're done
        break

    # add the sublist to the result and update `num`
    result.append(sublist)
    num = sublist[-1]

这将以线性O(n)时间运行,并给出预期结果:

[[0, 4], [4, 2, 9], [9, 10, 1], [1, 7, 5, 6, 11]]

答案 1 :(得分:0)

不是一个非常好的实现,但它可以工作:

my_list=[[9, 10, 1], [1, 7, 5, 6, 11], [0, 4], [4, 2, 9]]

new_list = []
index = 0
while my_list:
    index = [item[0] for item in my_list].index(index)
    item = my_list[index]
    del my_list[index]
    new_list.append(item)
    index = item[-1]
print(new_list)

如果未找到符合标准

的子列表,则会引发ValueError

答案 2 :(得分:0)

如果列表是有效的排列,您可以检查列表的每个排列。有可能编写一个更有效的算法,但这个算法并不假设只有一种可能的解决方案。

#include <stdio.h>

#define printf_dec_format(x) _Generic((x), \
    char: "%c", \
    signed char: "%hhd", \
    unsigned char: "%hhu", \
    signed short: "%hd", \
    unsigned short: "%hu", \
    signed int: "%d", \
    unsigned int: "%u", \
    long int: "%ld", \
    unsigned long int: "%lu", \
    long long int: "%lld", \
    unsigned long long int: "%llu", \
    float: "%f", \
    double: "%f", \
    long double: "%Lf", \
    char *: "%s", \
    void *: "%p")

#define print(x) printf(printf_dec_format(x), x)
#define printnl(x) printf(printf_dec_format(x), x), printf("\n");

int main(void) {
    printnl('a');    // prints "97" (on an ASCII system)
    printnl((char)'a');  // prints "a"
    printnl(123);    // prints "123"
    printnl(1.234);      // prints "1.234000"
    printnl("hello");
}

答案 3 :(得分:0)

    def sortList(list)
      hash = {}
      list.each do |value|
        hash[value[0]] = value
      end
      key = 0
      sorted = []
      list.each do |k|
        item = hash[key.to_i]
        key = item[-1]
        sorted << item
      end
      sorted
    end
相关问题