简体   繁体   English

根据另一个列表对列表进行排序

[英]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因为wd不是成对数据。

I have a code sample, and want to get t variable. 我有一个代码示例,并且想要获取t变量。

Updated 更新

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. 它们成对的数据,但方向相反。

  • Make a third list, i , np.arange(0, 10). 列出第三个列表i ,np.arange(0,10)。
  • zip this with d . d zip
  • Sort the tuples with d as the sort key; d作为排序键对元组进行排序; i still holds the original index of each d element. i仍然拥有每个d元素的原始索引。
  • zip this with w . w zip它。
  • Sort the triples (well, pairs with a pair as one element) with i as the sort key. i作为排序键对三元组(好吧,一对成对作为一个元素)进行排序。
  • Extract the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM