gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:56:05 25 4
gpt4 key购买 nike

尝试检索排序列表“第二”的索引。“first”包含与“first”相同的值,并且将被重新排序以变得与“first”相同的顺序。我正在寻找一个索引列表“d”,其中包含旧“第二”中重新排序的索引。

尝试使用 zip 或 enumerate 检索“d”,但失败。

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

这里“第二”的顺序与“第一”相同。凉爽的。但是如何从“second”中检索重新排序的索引列表“d”?

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

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

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

最佳答案

这是一种方法。

例如:

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 - 按另一个列表的顺序对 python 列表进行排序并检索旧索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56020701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com