链接列表&;python中的排序
下面是我想要的示例(Python 3.6): 按相同顺序链接到链接列表&;python中的排序,python,Python,下面是我想要的示例(Python 3.6): 按相同顺序链接到列表3 当List2按List1的顺序或按从最小到最大的顺序更改时的预期输出列表3也会改变 期望输出: List2=[1,2,3,4,5] #list change to correct order List3=[5,10,15,20,25] #list stayed in correct position linked with list2 您正在寻找argsort功能。在python中,实现这一点的一种方法是使用sorted+e
列表3
当List2
按List1
的顺序或按从最小到最大的顺序更改时的预期输出<代码>列表3也会改变
期望输出:
List2=[1,2,3,4,5] #list change to correct order
List3=[5,10,15,20,25] #list stayed in correct position linked with list2
您正在寻找argsort功能。在python中,实现这一点的一种方法是使用
sorted
+enumerate
:
>>> [List3[x] for x, _ in sorted(enumerate(List2), key=lambda x: x[1])]
[5, 10, 15, 20, 25]
使用
numpy
,您可以通过以下方式完成此操作:
>>> import numpy as np
>>> np.array(List3)[np.argsort(List2)]
array([ 5, 10, 15, 20, 25])
下面是在纯Python中执行此操作的另一种方法: 压缩这两个列表,然后按第一个(默认)元素排序 如果要按第二个元素排序,请执行以下操作:
result = [b for _, b in sorted(zip(List2, List3), key=lambda x: x[1])]
您正在寻找argsort功能。是否有此功能的链接或教程页?或者一个示例程序?
argsort
是numpy
包的一部分。numpy是内置的吗?到python@GraphicsLab,通过阅读python文档并理解其中的许多内容,您将受益匪浅。像max
、min
、sorted
、zip
这样的函数都有非常实用的应用程序,可以用来组合成各种各样的东西。阅读itertools和functools来获得一些想法。嗨,有没有办法不用下载和安装软件包就可以做到这一点?@GraphicsLab第一种技术不需要任何软件包。你有这样的例子吗?@GraphicsLab这在我的答案中[List3[x]对于x,uu.在排序(枚举(List2),key=lambda x:x[1])
@graphicsplab在编辑器中,您需要将表达式的返回值分配给变量并调用print
<代码>x=[……];print(x)说真的,你自己试试。我会试试[20]@graphicsplab中的位是什么,哦,我使用的是ipython
交互式shell。好了,伙计,我忘了第一个位,然后读:快来吧。我认为排序(zip…解决方案更优雅。:@graphicsplab,是的,Out[20]:
是shell的一部分,忽略它。
In [18]: List2=[5,4,3,2,1]
In [19]: List3=[25,20,15,10,5]
In [20]: [b for _, b in sorted(zip(List2, List3))]
Out[20]: [5, 10, 15, 20, 25]
result = [b for _, b in sorted(zip(List2, List3), key=lambda x: x[1])]