如何对列表中的元组列表进行排序?

时间:2016-01-11 13:45:13

标签: python-2.7 sorting tuples

我希望按优先顺序(*,/,+, - )对数学运算符元组(存储为字符串)及其索引的列表进行排序,同时保留其原始索引。我的列表中有数以千计的元组列表。

E.g。

my_lists = [[(0,'*'),(1,'+'),(2,'-')],[(0,'-'),(1,'*'),(2,'*')],[(0,'+'),(1,'/'),(2,'-')]]

应该成为:

new_list = [[(0,'*'),(1,'+'),(2,'-')],[(1,'*'),(2,'*'),(0,'-')],[(1,'/'),(0,'+'),(2,'-')]]

我尝试过使用'sorted'内置函数并将优先级存储在字典中。

priority = {'*': 0, '/': 1, '+': 2, '-': 3}

new_list = [sorted(item, key = priority.get) for item in my_lists]

这会生成相同的原始列表。

如何在排序元组列表时只访问元组的运算符部分?

1 个答案:

答案 0 :(得分:1)

您正在使用整个元组作为键进行排序,例如(0, '*')。您只能使用它的第二部分(即x[1]):

[sorted(item, key = lambda x: priority.get(x[1])) for item in my_lists]

返回

[[(0, '*'), (1, '+'), (2, '-')],
 [(1, '*'), (2, '*'), (0, '-')],
 [(1, '/'), (0, '+'), (2, '-')]]

您的代码没有抛出错误,因为priority.get((0, '*'))是合法的并返回None,这在Python 2.7中是完全可排序的,并使列表保持原始顺序。

相关问题