Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

Python list rearrange the elements in a required order

My main list has 44 names as elements. I want to rearrange them in a specific order. I am giving here an example. Note that elements in my actual list are some technical names. No way related to what I have given here.

main_list = ['one','two','five','six',.................'twentyone','three','four','seven','eight',.....,'fortyfour']

I want to rearrange the list. I have no idea how to proceed. But my expected output should like this Expected output:

main_list = ['one','two','three','four','five','six','seven','eight'.................'twentyone',,.....,'fortyfour']
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can have a dictionary to use as your sorting key:

sort_keys = {
    'one': 1,
    'two': 2,
    'three': 3,
    'ten': 10,
    'twenty': 20,
}
main_list = ['twenty', 'one', 'three', 'ten', 'two']
main_list.sort(key=lambda i: sort_keys[i])
print(main_list)

Output:

['one', 'two', 'three', 'ten', 'twenty']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...