[英]Sort list based on another list
I have two lists in python3.6, and I would like to sort w
by considering d
values. 我在python3.6中有两个列表,我想通过考虑
d
值对w
进行排序。 This is similar to this question, Sorting list based on values from another list? 这类似于这个问题, 基于另一个列表中的值对列表进行排序? , though, I could not use
zip
because w
and d
are not paired data. ,但是,我无法使用
zip
因为w
和d
不是成对数据。
I have a code sample, and want to get t
variable. 我有一个代码示例,并且想要获取
t
变量。
I could do it by using for loop. 我可以通过使用for循环来做到这一点。 Is there any fasterh way?
有没有更快的方法?
import numpy as np
w = np.arange(0.0, 1.0, 0.1)
t = np.zeros(10)
d = np.array([3.1, 0.2, 5.3, 2.2, 4.9, 6.1, 7.7, 8.1, 1.3, 9.4])
ind = np.argsort(d)
print('w', w)
print('d', d)
for i in range(10):
t[ind[i]] = w[i]
print('t', t)
#w [ 0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
#d [ 3.1 0.2 5.3 2.2 4.9 6.1 7.7 8.1 1.3 9.4]
#ht [ 0.3 0. 0.5 0.2 0.4 0.6 0.7 0.8 0.1 0.9]
Use argsort
like so: 像这样使用
argsort
:
>>> t = np.empty_like(w)
>>> t[d.argsort()] = w
>>> t
array([0.3, 0. , 0.5, 0.2, 0.4, 0.6, 0.7, 0.8, 0.1, 0.9])
They are paired data, but in the opposite direction. 它们是成对的数据,但方向相反。
i
, np.arange(0, 10). i
,np.arange(0,10)。 zip
this with d
. d
zip
。 d
as the sort key; d
作为排序键对元组进行排序; i
still holds the original index of each d
element. i
仍然拥有每个d
元素的原始索引。 zip
this with w
. w
zip
它。 i
as the sort key. i
作为排序键对三元组(好吧,一对成对作为一个元素)进行排序。 w
values in their new order; w
值; this is your t
array. t
数组。 The answers for this question are fantastic, but I feel it is prudent to point out you are not doing what you think you are doing. 这个问题的答案很棒,但是我要谨慎地指出您没有按照自己的想法去做。
What you want to do: (or at least what I gather) You want t
to contain the values of w
rearranged to be in the sorted order of d
您想做什么:( 或至少是我收集的)您想让
t
包含以d
的排序顺序重新排列的w
的值
What you are doing: Filling out t
in the sorted order of d
, with elements of w
. 你在做什么:填写
t
中的排序顺序d
,用的元素w
。 You are only changing the order of how t
gets filled up. 您仅在更改
t
填充方式的顺序。 You are not reflecting the sort of d
into w
on t
您没有将
d
反映为w
on t
Consider a small variation in your for
loop 考虑一下
for
循环中的一个小变化
for i in range(0,10):
t[i] = w[ind[i]]
This outputs a t
这输出一个
t
('t', array([0.1, 0.8, 0.3, 0. , 0.4, 0.2, 0.5, 0.6, 0.7, 0.9]))
You can just adapt PaulPanzer's answer to this as well. 您也可以调整PaulPanzer的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.