jcd*_*rbm 4 python sorting list python-2.7
我想按列表中的优先顺序(*,/,+, - )对数学运算符列表(存储为字符串)进行排序.我的列表中有数千个列表.
例如
my_lists = [['*','+','-'],['-','*','*'],['+','/','-']]
Run Code Online (Sandbox Code Playgroud)
应成为:
new_list = [['*','+','-'],['*','*','-'],['/','+','-']]
Run Code Online (Sandbox Code Playgroud)
有没有办法按用户定义的顺序对列表中的列表进行排序?
我们的想法是创建一个新的运算符列表,并将运算符存储在您想要的所需优先级中(您可以随时更改优先级),然后使用运算符索引作为key
排序.
你可以简单地通过传递key
给sort函数来做到:
my_lists = [['*','+','-'],['-','*','*'],['+','/','-']]
operators = ['*', '/', '+', '-']
new_list = [sorted(i, key = operators.index) for i in my_lists]
>>> [['*', '+', '-'], ['*', '*', '-'], ['/', '+', '-']]
Run Code Online (Sandbox Code Playgroud)
但是你在问题中提到了一个元组(*,/,+,-)
,所以我尝试使用列表来解决问题,但是使用字典会更加清晰,因为@thefourtheye建议.
您可以使用字典定义优先级,如下所示
>>> priority = {'*': 0, '/': 1, '+': 2, '-': 3}
Run Code Online (Sandbox Code Playgroud)
然后使用来自的值对单个列表进行排序priority
,如下所示
>>> [sorted(item, key=priority.get) for item in my_lists]
[['*', '+', '-'], ['*', '*', '-'], ['/', '+', '-']]
Run Code Online (Sandbox Code Playgroud)