簡體   English   中英

從1D列表創建2D索引列表

[英]Creating a 2D list of indices from a 1D list

我有一個整數列表x ,我想創建一個整數2D清單y從它。 這里, y中的每一行ix中具有值i的元素的索引的列表。

例如,如果:

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

然后:

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

我怎樣才能在Python中巧妙地做到這一點?

這很簡單:

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

我們列出正確數量的列表,然后將每個索引添加到相應的子列表中。

或者使用列表理解:

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)]

這是我的快速解決方案

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)

強制性的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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM