迭代Python中的子列表子列表

时间:2016-01-14 23:16:26

标签: python sorting python-3.x nested-lists

我有一个整数列表,所有整数都被分成k个子列表,直到每个子列表的长度为1。 我的目标是使用一个排序算法,该算法采用k的参数和长度> 1的排序列表。 0(例如list = [[1,4,8],[2,3,7],[5,6,9]])。 例如:

list = [[[5], [2], [4]], [[9], [1], [8]], [[7], [6], [3]]]
k = 3

应用排序算法后:

list = [[2, 4, 5], [1, 4, 9], [3, 6, 7]]

应用排序算法后:

list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print('Sorted list: ', list)

我已经尝试迭代最低级别的子列表日志(len(list),k),但最终陷入了递归循环。我在python方面不是很有经验,觉得会有某种捷径。

编辑: 我知道这是很多代码,但我不知道如何解释自己:

from math import *
input_list = [[[5], [2], [4]], [[9], [1], [8]], [[7], [6], [3]]]
result = []
numbers = 9
k = 3
new_list = []

def merge(k, list):#---------------for list [[ordered], [ord..], [ord..]]
    global result
    while len(list) > 0:
        b = 0
        low = min(list)
        x = list.index(low)

        for sub_list in list:
            if b == x:
                result.append(sub_list[b])
                sub_list.pop(0)
                list = [x for x in list if x != []]

            b+=1
    print('Final list: ', list)
    print('Final result: ', result)

def split_list(input_list, k):
    if len(input_list) == 1:
        return input_list
    segment = len(input_list) // k
    return [split_list(input_list[i:i+segment], k) 
            for i in range(0, len(input_list), segment)]


def merge_sort(k, list):
    iterations = log(numbers, k)
    a = 0
    for sub_list in list:
        if a < iterations:
            list = list[0]
            a += 1
        else:
            merge(k, sub_list)

list = split_list(input_list, k)
print(merge_sort(k, list))
print(list)

我的merge()函数完全正常,但是我不知道如何遍历未知数量的子列表以使我的merge_sort()工作。

编辑2: 关于扁平化的建议,我仍在调查,但我认为这不会对我的情况有所帮助。在我的合并功能中,子列表在末尾被展平。例如:

k = 3
list = [[5], [2], [4]]
print(merge(k, sub_lists))

会产生[2,4,5]

的输出

0 个答案:

没有答案
相关问题