[英]Arrange list of strings that are divided into 4 parts by the different parts?
I have a list comprised of strings that all follow the same format 'Name%Department%Age' 我有一个由字符串组成的列表,所有字符串都遵循相同的格式'Name%Department%Age'
I would like to order the list by age, then name, then department. 我想按年龄,姓名,部门排序。
alist = ['John%Maths%30', 'Sarah%English%50', 'John%English%30', 'John%English%31', 'George%Maths%30']
after sorting would output: 排序后将输出:
['Sarah%English%50, 'John%English%31', 'George%Maths%30', 'John%English%30, 'John%Maths%30']
The closest I have found to what I want is the following (found here: How to sort a list by Number then Letter in python? ) 我找到的最接近我想要的是以下内容(在这里找到: 如何在Python中按数字然后按字母对列表进行排序? )
import re
def sorter(s):
match = re.search('([a-zA-Z]*)(\d+)', s)
return int(match.group(2)), match.group(1)
sorted(alist, key=sorter)
Out[13]: ['1', 'A1', '2', '3', '12', 'A12', 'B12', '17', 'A17', '25', '29', '122']
This however only sorted my layout of input by straight alphabetical. 但是,这仅按直字母顺序对我的输入布局进行排序。
Any help appreciated, 任何帮助表示赞赏,
Thanks. 谢谢。
You are on the right track. 您走在正确的轨道上。
Personally, I: 我个人:
string.split()
to chop the string up into its constituent parts; 首先使用string.split()
将字符串切成其组成部分; For example: 例如:
def key(name_dept_age):
name, dept, age = name_dept_age.split('%')
return -int(age), name, dept
alist = ['John%Maths%30', 'Sarah%English%50', 'John%English%30', 'John%English%31', 'George%Maths%30']
print(sorted(alist, key=key))
Use name, department, age = item.split('%')
on each item. 在每个项目上使用name, department, age = item.split('%')
。
Make a dict out of them {'name': name, 'department': department, 'age': age}
从他们中做出一个命令{'name': name, 'department': department, 'age': age}
Then sort them using this code https://stackoverflow.com/a/1144405/277267 然后使用此代码对它们进行排序https://stackoverflow.com/a/1144405/277267
sorted_items = multikeysort(items, ['-age', 'name', 'department'])
Experiment once with that multikeysort
function, you will see that it will come in handy in a couple of situations in your programming career. 尝试使用该multikeysort
功能后,您会发现它在编程生涯中的某些情况下会派上用场。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.