正如@NullUserException 所说,您不能分两步进行排序,因为第二步将仅基于中间列重新洗牌,而忽略第一列(str)。
您可以在适当地转换数据后一次性进行排序,并且您不必担心键:
s='''ABC - 0.2 - 15
BAC - 1.2 - 10
ABC - 1.3 - 29
ABC - 0.7 - 11'''
data = s.split('\n')
data
Out[5]: ['ABC - 0.2 - 15', 'BAC - 1.2 - 10', 'ABC - 1.3 - 29', 'ABC - 0.7 - 11']
newdata = [(i[0],float(i[1]),i[2]) for i in [k.split(' - ') for k in data]]
newdata
Out[10]:
[('ABC', 0.2, '15'),
('BAC', 1.2, '10'),
('ABC', 1.3, '29'),
('ABC', 0.7, '11')]
sorted(newdata)
Out[11]:
[('ABC', 0.2, '15'),
('ABC', 0.7, '11'),
('ABC', 1.3, '29'),
('BAC', 1.2, '10')]
另一种方法:如果输入数据重组需要大量操作,则使用 lambda 键可能是更简单的方法:
# data is a list of strings
data = ['ABC - 0.2 - 15', 'BAC - 1.2 - 10', 'ABC - 1.3 - 29', 'ABC - 0.7 - 11']
# My key is now a lambda function that extracts the
# sortable parts, and assembles them in a tuple.
# Note how easy it would be to change the sort order,
# just order the entries in the inner tuple differently.
# If data is some other array-like structure, just change
# how the inner data is accessed when building your tuple.
sorted(data, key=lambda x: (x.split(' - ')[0], float(x.split(' - ')[1])))
Out[18]: ['ABC - 0.2 - 15', 'ABC - 0.7 - 11', 'ABC - 1.3 - 29', 'BAC - 1.2 - 10']