如何根据第二个索引列表重新排列一个列表 [英] How to rearrange one list based on a second list of indices

查看:52
本文介绍了如何根据第二个索引列表重新排列一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含10个项目的列表,还有另一个包含10个随机不重复的数字的列表,如下所示:

I have a list of 10 items, and another list of 10 randomly not repeated numbers as following:

l = [a,b,c,d,e,f,g,h,i,j]
m = [1,4,5,9,2,6,3,7,8,10]

我想重新排列l,以便l中的每个项目都从m获取其对应的索引.

I want to rearrange l, so that each item in l takes its corresponding index from m.

例如,b应该成为第四,而e应当成为第二.

For example, b should become the fourth and e sould become the second.

我真的被算法困住了,逻辑困扰了我,所以我对如何处理这个问题一无所知.

I'm really stuck at the algorithm and the logic bugs me, so I don't have any idea on how to approach thi.

我该怎么做?

推荐答案

如果您只是试图根据其他列表位置移动元素,则可以循环遍历m的所有元素并获取l使用列表理解

If you're just trying to get elements moved around based on the other lists positions, you can loop over all elements of m and grab that element of l using list comprehension

l2 = [l[i - 1] for i in m] 

但是,如果您希望基于其他列表进行排序,则需要将它们压缩在一起,对索引进行排序,然后提取元素

But if you do want the ordering based on the other list, you're going to need to zip them together, sort on the index, then extract the elements

[y for x,y in sorted(zip(m,l))] 

这篇关于如何根据第二个索引列表重新排列一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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