Python的到位排序并行阵列? [英] Python sort parallel arrays in place?
问题描述
有一个简单的(意思是不滚动自己的排序功能)的方式来进行排序并行名单没有不必要的复制在Python?例如:
Is there an easy (meaning without rolling one's own sorting function) way to sort parallel lists without unnecessary copying in Python? For example:
foo = range(5)
bar = range(5, 0, -1)
parallelSort(bar, foo)
print foo # [4,3,2,1,0]
print bar # [1,2,3,4,5]
我已经看到了使用拉链的例子
但似乎很傻,从平行列出了所有的数据复制到一个元组列表,然后再返回,如果这可以很容易地避免
I've seen the examples using zip
but it seems silly to copy all your data from parallel lists to a list of tuples and back again if this can be easily avoided.
推荐答案
下面是一个简单的方法:
Here's an easy way:
perm = sorted(xrange(len(foo)), key=lambda x:foo[x])
这会产生排列的列表 - 彼尔姆[I]的值在foo中第i个最小值的指标。然后,您可以访问,以便两个列表:
This generates a list of permutations - the value in perm[i] is the index of the ith smallest value in foo. Then, you can access both lists in order:
for p in perm:
print "%s: %s" % (foo[p], bar[p])
您就需要基准它来看看它的任何更有效,但 - 我怀疑它使多大的差别
You'd need to benchmark it to find out if it's any more efficient, though - I doubt it makes much of a difference.
这篇关于Python的到位排序并行阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!