如何重新排序列表? [英] How can I reorder a list?

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

问题描述

如果我有一个列表 [a,b,c,d,e] 我怎样才能像 [d,c,a,b,e 那样以任意方式重新排序项目]?

If I have a list [a,b,c,d,e] how can I reorder the items in an arbitrary manner like [d,c,a,b,e]?

我不想洗牌.我想以预定义的方式重新排序它们.(例如,我知道旧列表中的第 3 个元素应该成为新列表中的第一个元素)

I don't want to shuffle them. I want to re-order them in a predefined manner. (for example, I know that the 3rd element in the old list should become the first element in the new list)

推荐答案

你可以这样做

mylist = ['a', 'b', 'c', 'd', 'e']
myorder = [3, 2, 0, 1, 4]
mylist = [mylist[i] for i in myorder]
print(mylist)         # prints: ['d', 'c', 'a', 'b', 'e']

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

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