简体   繁体   English

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

[英]How to partition a list based on (sublist) indices of another list in Python

I have two lists, one containing some unique elements (integers in my case) and the other containing indices that indicate into which sublist of a newly created nested list the elements should be inserted.我有两个列表,一个包含一些独特的元素(在我的例子中是整数),另一个包含指示元素应该插入到新创建的嵌套列表的哪个子列表中的索引。

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

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

The list of elements contains only unique items, potentially not sorted.元素列表仅包含唯一项,可能未排序。 The list of indices is 'normalized' such that the lower indices will always occur first.索引列表是“标准化的”,这样较低的索引将始终首先出现。 The new nested list should use the indices to determine the sublist of the expected result to which the elements shall belong.新的嵌套列表应使用索引来确定元素所属的预期结果的子列表。

I have come up with the following function, but I have a feeling that there should be an easier way.我想出了以下功能,但我觉得应该有一个更简单的方法。

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

Can anyone think of an easier, maybe more pythonic way of achieving the same result?任何人都可以想出一种更简单,也许更像 Pythonic 的方法来实现相同的结果吗?

Try using this for loop with zip :尝试使用带有zip for 循环:

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

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何根据另一个列表中的索引从列表中获取子列表? - How to get a SubList from a list based on indices in another List? 如何根据另一个列表中的索引从列表中删除子列表? - How to remove sublist from a list based on indices in another list? 如何根据索引值从另一个列表中提取子列表 - How to extract a sublist from another list based on value with indices 如何获取基于另一个列表的列表的子列表? - How to get a sublist of a list based on another list? 获取具有给定索引的Python列表的子列表? - Getting a sublist of a Python list, with the given indices? Python:查找与给定子列表匹配的列表索引 - Python: finding the indices of a list that match the given sublist 在 Python 中查找另一个列表中多次出现或无的项目列表的索引子列表 - Find sublist of indices for a list of items in another list with multiple occurrences or None in Python 如何删除嵌套列表中另一个子列表中的子列表? - How to remove a sublist in nested list that are in another sublist? 在python中查找2d列表的索引,其中包含另一个特定的子列表 - Find indices of a 2d list in python, which contain another particular sublist 如何在python中将列表拆分为子列表 - How to split the list into sublist in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM