[英]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.