python按顺序读取list_按另一个列表的顺序对python列表进行排序并检索旧索引

1586010002-jmsa.png

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".

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)]

Here "second" become same order as "first". Cool.

But how can I retrieve the reorderd Indexlist "d" from "second"?

I tried like:

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

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?

解决方案

This is one approach.

Ex:

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)

Output:

[(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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值