根据索引和内部列表的长度对嵌套列表进行分类

时间:2017-06-01 10:22:29

标签: python list sorting

我想根据各自的索引和内部列表的长度对嵌套列表进行分类。

例如,如果初始列表如下:

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

我想制作两个新的嵌套列表,每个列表中的内部列表与初始列表的数量相同,而内部列表的长度相同。此外,列表的索引顺序应该与初始列表保持相同,并且对于每个非等长列表的长度,我希望有一个列表,其值为其先前列表。

所以,基本上我希望输出如下:

a1=[[1,2,3],[4,5,6],[4,5,6],[4,5,6],[5,6,7],[1,3,5]]

a2=[[3,4],[3,4],[3,4],[2,1],[2,1],[2,1]]

是否有合理的方法来解决这个问题?

1 个答案:

答案 0 :(得分:1)

这里有一个示例,它以子列表长度为关键字生成dict,并列出具有所述长度的所有子列表:

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

lengths = set([len(l) for l in a])
result = { n : [l for l in a if len(l) == n] for n in lengths}

print(result)

这给出了:

{2: [[3, 4], [2, 1]], 3: [[1, 2, 3], [4, 5, 6], [5, 6, 7], [1, 3, 5]]}

修改

如果要为列表命名,可以使用

执行此操作
a1 = result[2] #[[3, 4], [2, 1]]
a2 = result[3] #[[1, 2, 3], [4, 5, 6], [5, 6, 7], [1, 3, 5]]

编辑2

在了解了OP要求的内容之后,这里有一个产生所需结果的代码:

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

lengths = set([len(l) for l in a])

result = { n : [l for l in a if len(l) == n] for n in lengths}

iter_2 = iter(result[2])
current_2 = result[2][0]
iter_3 = iter(result[3])
current_3 = result[3][0]

a1 = []
a2 = []


for l in a:

    if len(l) == 2:
        current_2 = next(iter_2)
    elif len(l) == 3:
        current_3 = next(iter_3)

    a1.append(current_2)
    a2.append(current_3)

print(a1) #[[3, 4], [3, 4], [3, 4], [2, 1], [2, 1], [2, 1]]
print(a2) #[[1, 2, 3], [4, 5, 6], [4, 5, 6], [4, 5, 6], [5, 6, 7], [1, 3, 5]]

编辑3

没有迭代器的另一种方法是:

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

a1=[l if len(l) == 2 else None for l in a]
a2=[l if len(l) == 3 else None for l in a]

for l in a1:
    if l is not None:
        curr1 = l
        break

for l in a2:
    if l is not None:
        curr2 = l
        break

for i in range(len(a)):
    if a1[i] is None:
        a1[i] = curr1
    else:
        curr1 = a1[i]

    if a2[i] is None:
        a2[i] = curr2
    else:
        curr2 = a2[i]

print(a1) #[[3, 4], [3, 4], [3, 4], [2, 1], [2, 1], [2, 1]]
print(a2) #[[1, 2, 3], [4, 5, 6], [4, 5, 6], [4, 5, 6], [5, 6, 7], [1, 3, 5]]

编辑4

显然我有点沮丧,但这里仍然是一个适用于任何类型的子列表长度的通用解决方案:

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

lengths = set([len(l) for l in a])
result = { n : [l if len(l) == n else None for l in a] for n in lengths}
current = {}

for n,res in result.items():
    for l in res:
        if l is not None:
            current[n] = l
            break


for i in range(len(a)):
    for n,res in result.items():
        if res[i] is None:
            res[i] = current[n]
        else:
            current[n] = res[i]

print(result)

给出:

{
  2: [[3, 4], [3, 4], [3, 4], [2, 1], [2, 1], [2, 1]], 
  3: [[1, 2, 3], [4, 5, 6], [4, 5, 6], [4, 5, 6], [5, 6, 7], [1, 3, 5]]
}