[英]Whats the most efficient pythonic way to do this :
I've a list L
of size N
where each element of the list is between 0
to K-1
. 我有一个大小为N
的列表L
,其中列表的每个元素在0
到K-1
。
I want to create a 2D list S
with K
rows such that r
th row contains all those indices i
, such that L[i] == r
. 我想用K
行创建一个2D列表S
,使第 r
行包含所有这些索引i
,从而使L[i] == r
。
For example if L
was [0, 0, 1, 3, 0, 3]
例如,如果L
为[0, 0, 1, 3, 0, 3]
then the new list S
is [[0, 1, 4], [2], [], [3, 5]]
那么新列表S
为[[0, 1, 4], [2], [], [3, 5]]
Solution should of course be O(N), it should also be as efficient as possible (Read : no useless append operations on list) 解决方案当然应该是O(N),它也应该尽可能高效(阅读:列表上没有无用的附加操作)
>>> L = [0, 0, 1, 3, 0, 3]
>>> import collections
>>> d = collections.defaultdict(list)
>>> for index, item in enumerate(L):
... d[item].append(index)
...
>>> d
defaultdict(<type 'list'>, {0: [0, 1, 4], 1: [2], 3: [3, 5]})
>>> [d[i] for i in xrange(1 + max(d))]
[[0, 1, 4], [2], [], [3, 5]]
>>> L = [0, 0, 1, 3, 0, 3]
>>> S = map(lambda x: [], L)
>>> S
[[], [], [], [], [], []]
>>> for index, item in enumerate(L):
S[item].append(index)
>>> S
[[0, 1, 4], [2], [], [3, 5], [], []]
>>>
With this solution, all indexes of S
from 0
to K - 1
are filled in with an empty list. 使用此解决方案,从0
到K - 1
的S
所有索引都用一个空列表填充。
EDIT: indeed wim is right, S[4]
and S[5]
are not desired so I reused wim's xrange
to make it work as desired: 编辑:的确wim是正确的,不需要S[4]
和S[5]
,所以我重用了wim的xrange
以使其按需工作:
>>> L = [0, 0, 1, 3, 0, 3]
>>> S = map(lambda x: [], xrange(1 + max(L)))
...
>>> S
[[0, 1, 4], [2], [], [3, 5]]
Here's a simple but efficient way to do it: 这是一种简单但有效的方法:
K = 4
S = [ [] for _ in range(K) ]
for n, val in enumerate(L):
S[val].append(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.