python - 如何根据 Python 中另一个列表的(子列表)索引对列表进行分区

标签 python list nested partition

我有两个列表,一个包含一些独特的元素(在我的例子中是整数),另一个包含指示应将元素插入到新创建的嵌套列表的子列表中的索引。

elements = [1, 2, 3, 4, 5, 6]
indices =  [0, 0, 1, 2, 2, 1]

expected_result = [[1, 2], [3, 6], [4, 5]]

元素列表仅包含唯一项,可能未排序。 索引列表是“规范化”的,因此较低的索引总是先出现。 新的嵌套列表应该使用索引来确定元素所属的预期结果的子列表。

我想出了以下功能,但我觉得应该有更简单的方法。

def indices_to_nested_lists(indices: Sequence[int], elements: Sequence):
    result = []
    for i in range(max(indices)+1):
        sublist = []
        for j in range(len(elements)):
            if indices[j] == i:
                sublist.append(elements[j])
        result.append(sublist)
    return result

谁能想出一种更简单、也许更 Python 化的方法来实现相同的结果?

最佳答案

尝试将此 for 循环与 zip 一起使用:

l = [[] for i in range(max(indices) + 1)]
for x, y in zip(elements, indices):
    l[y].append(x)
print(l)

输出:

[[1, 2], [3, 6], [4, 5]]

关于python - 如何根据 Python 中另一个列表的(子列表)索引对列表进行分区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68389600/

相关文章:

java - 如何在java中显示链接列表中的项目

python - 在 python 上,如何在加入 float 列表后去掉引号?

iphone - 枚举二级 NSDictionaries

python - 在字典中的列表值内添加整数

r - 将向量列表组合到 data.frame 中,并带有列表编号

python - 如何循环嵌套字典列表并带来 k :v pairs to 1st-level dictionary? JSON 数据

python - 在 Python 中动态更改未知深度的嵌套列表中的特定项目

python - 找出第 20、30、n 个素数。 (我得到第 20 名而不是第 30 名?)[Python]

python - 主管错误 "child process was not spawned"

python - celery 异常处理