3

假设我有

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

我期待

c = [[4,9],[7,6,11],[5]]

如您所见,生成的子列表位于 list 指向的索引处a。我们在 python 中会怎么做?

4

2 回答 2

5

您可以使用defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = [1,1,1,2,2,3]
>>> b = [4,7,9,5,6,11]
>>> for k,v in zip(a,b):
...     d[k].append(v)
... 
>>>[x[1] for x in sorted(d.items())]
[[4, 7, 9], [5, 6], [11]]
于 2013-05-10T13:42:17.507 回答
2

IIUC,我会简单地遍历这些术语:

def combine(a,b):
    c = [[] for _ in range(max(a))]
    for i, elem in zip(a, b):
        c[i-1].append(elem)
    return c

这使

>>> a = [1, 1, 1, 2, 2, 3]
>>> b = [4, 7, 9, 5, 6, 11]
>>> combine(a,b)
[[4, 7, 9], [5, 6], [11]]
>>> a = [1,2,1,3,2,2]
>>> b = [4,7,9,5,6,11]
>>> combine(a,b)
[[4, 9], [7, 6, 11], [5]]
于 2013-05-10T13:40:51.740 回答