从一维列表创建二维索引列表

时间:2016-04-08 19:40:48

标签: python

我有一个整数列表x,我想从中创建一个整数y的2D列表。此处i中的每一行y都是x中元素的索引列表,其值为i

例如,如果:

x = [2, 0, 1, 1, 2, 4],

然后:

y = [[1], [2, 3], [0, 4], [], [5]]

我怎样才能在Python中巧妙地做到这一点?

4 个答案:

答案 0 :(得分:2)

这很简单:

y = [[] for _ in xrange(max(x)+1)]
for i, item in enumerate(x):
    y[item].append(i)

我们列出正确数量的列表,然后将每个索引添加到相应的子列表中。

答案 1 :(得分:2)

或使用列表理解:

x = [2, 0, 1, 1, 2, 4]
y = [[j for j in range(len(x)) if x[j]==i] for i in range(max(x)+1)]

答案 2 :(得分:1)

这是我的快速解决方案

x = [2, 0, 1, 1, 2, 4]

y = []
for i, k in enumerate(x):
    if len(y) - 1 < k: #if our list isn't long enough for this value
        while (len(y) - 1 != k):
            y.append([]) #make it long enough
    y[k].append(i) #append our current index to this values list

print (y)

答案 3 :(得分:1)

强制性的numpy答案(argwhere的完美案例):

import numpy as np
x = np.array([2, 0, 1, 1, 2, 4])
print [np.argwhere(x == i).flatten().tolist() for i in range(np.max(x)+1)]