按另一个列表的顺序对python列表进行排序并检索旧索引 [英] Sort python list by order of another list AND retrieve old index

查看:1030
本文介绍了按另一个列表的顺序对python列表进行排序并检索旧索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图检索排序列表第二"的索引. 第二"包含与第一"相同的值,并且将重新排序以成为与第一"相同的顺序.我正在寻找索引列表"d",其中包含旧第二"中重新排序的索引.

Trying to retrieve the index of sorted list "second". "second" contains same values as "first" and will be reordered to become identical order as "first". I'm looking for an indexlist "d" which contains the the reordered indexes from old "second".

尝试使用zip或枚举检索"d",但失败.

tryied to retrieve "d" with zip or enumerate, but failed.

first= [(11.373,0.354,6.154),(22.354,0.656,0.664),(33.654,33.546,31.131)]
second=[(22.354,0.656,0.664),(33.654,33.546,31.131),(11.373,0.354,6.154)]

second=sorted(second,key=first.index)

print(first)
print(second)
[(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]
[(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]

此处第二"与第一"的顺序相同.凉爽的. 但是,如何从第二个"中检索重新排序的索引列表"d"?

Here "second" become same order as "first". Cool. But how can I retrieve the reorderd Indexlist "d" from "second"?

我尝试过: d = [i [0] for i in sorted(enumerate(second),key = first.index)]

I tried like: d = [i[0] for i in sorted(enumerate(second), key=first.index)]

在此示例中,"d"应变为[2,0,1]

In this example "d" should become [2,0,1]

这种类型的键在某种程度上阻止了检索旧索引的可能性.有什么建议吗?

This type of key is somehow blocking the possibility to retriev the old index. Any recommendation?

推荐答案

这是一种方法.

例如:

first= [(11.373,0.354,6.154),(22.354,0.656,0.664),(33.654,33.546,31.131)]
second=[(22.354,0.656,0.664),(33.654,33.546,31.131),(11.373,0.354,6.154)]

temp = sorted(second,key=first.index)            #Sorted List. 
d = list(map(lambda x: second.index(x), temp))   #Fetch index from temp

print(first)
print(temp)
print(d)

输出:

[(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]
[(11.373, 0.354, 6.154), (22.354, 0.656, 0.664), (33.654, 33.546, 31.131)]
[2, 0, 1]

这篇关于按另一个列表的顺序对python列表进行排序并检索旧索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆