【问题标题】:How to partition a list based on (sublist) indices of another list in Python如何根据 Python 中另一个列表的(子列表)索引对列表进行分区
【发布时间】:2021-09-24 02:42:48
【问题描述】:

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

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 的方式来实现相同的结果?

【问题讨论】:

    标签: python list nested partition


    【解决方案1】:

    尝试将此 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]]
    

    【讨论】:

    • TypeError: can only concatenate list (not "int") to list。我收到一个错误
    • 这只是一个错字——应该是l = [[] for i in range(max(indices) + 1)]。这是一个很好的答案。您也可以将该行写为l = [[]] * (max(indices) + 1)
    • 啊,是的好多了!谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 2021-07-14
    • 1970-01-01
    • 2016-09-28
    • 2021-05-02
    相关资源
    最近更新 更多