1d列表索引python:增强MaskableList [英] 1d list indexing python: enhance MaskableList
问题描述
我的常见问题如下:
作为输入我有( n
是一些int > 1
)
As input I have (n
is some int >1
)
W = numpy.array(...)
L = list(...)
其中
len(W) == n
>> true
shape(L)[0] == n
>> true
我想对列表进行排序 L
关于 W
的值和比较器。我的想法是做以下事情:
And I want to sort the list L
regarding the values of W
and a comparator. My idea was to do the following:
def my_zip_sort(W,L):
srt = argsort(W)
return zip(L[srt],W[srt])
这应该像这个:
a = ['a', 'b', 'c', 'd']
b = zeros(4)
b[0]=3;b[1]=2;b[2]=[1];b[3]=4
my_zip_sort(a,b)
>> [(c,1)(b,2)(a,3)(d,4)]
但这不是,因为
TypeError: only integer arrays with one element can be converted to an index
因此,我需要做另一个循环:
thus, I need to do another loop:
def my_zip_sort(W,L):
srt = argsort(W)
res = list()
for i in L:
res.append((L[srt[i]],W[srt[i]]))
return res
我找到了一个主题关于 MaskableList
,但这对我不起作用(正如你可以在评论中看到的那样),因为我不仅需要保存或丢弃我的列表的特定值,但也需要重新订购它们:
I found a thread about a MaskableList
, but this does not work for me (as you can read in the comments), because I would not only need to hold or discard particular values of my list, but also need to re-order them:
a.__class__
>> msk.MaskableList
srt = argsort(b)
a[srt]
>> ['a', 'b', 'd']
结束:
我想找到一种方法,通过数组中的约束对对象的
。我自己找到了一种方法,除了列表索引之外,这种方式很好。你能帮我写一个类似于列表
进行排序 MaskableList
的类来完成这项任务,它具有良好的性能吗?
Concluding:
I want to find a way to sort a list
of objects by constraints in an array
. I found a way myself, which is kind of nice except for the list-indexing. Can you help me to write a class that works likewise to MaskableList
for this task, which has a good performance?
推荐答案
您不需要扩展列表
请避免
- 循环。一个 list-comprehension
就足够了,如果你期望一个新的列表
元组
:
You don't need to extend list
do avoid the for
-loop. A list-comprehension
is sufficient and probably the best you can do here, if you expect a new list
of tuples
:
def my_zip_sort(W, L):
srt = argsort(W)
return [(L[i], W[i]) for i in srt]
示例:
n = 5
W = np.random.randint(10,size=5)
L = [chr(ord('A') + i) for i in W]
L # => ['A', 'C', 'H', 'G', 'C']
srt = np.argsort(W)
result = [(L[i], W[i]) for i in srt]
print result
[('A', 0), ('C', 2), ('C', 2), ('G', 6), ('H', 7)]
这篇关于1d列表索引python:增强MaskableList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!