很多很好的答案。如果您这样做只是为了例如缘故或快速的一次性解析或家庭作业,那么它们都说明字符串处理/排序很好。但是,如果您真的要围绕轮胎管理构建一个真正的应用程序,我会考虑为您的轮胎制作一个真实的轮胎模型:
from ast import literal_eval
from operator import attrgetter
# Make a real object, because we can, and it's easy, and a real object is almost always better than abusing literal types
class Tire(object):
def __init__(self, width = 0, profile = 0, radius = 0): #now we have meaningful names to our indexed fields
self.width = width
self.profile = profile
self.radius = radius
# let's encapsulate the '{width}/{profile}/{radius}' string representation
# as an attribute so we can access/set it like the "real" attributes
@property
def description(self):
return '{}/{}/{}'.format(self.width, self.profile, self.radius)
@description.setter
def description(self, string):
self.width, self.profile, self.radius = map(literal_eval, string.split('/')) #ast.literal_eval() is safer than just eval()
# let's make a class side instance creation method that can instantiate and set the description directly too
@classmethod
def fromDescription(me, descriptionString):
newTire = me()
newTire.description = descriptionString
return newTire
#your original sample input
descriptions = ['285/30/18', '285/30/19', '235/40/17', '315/25/19', '275/30/19']
#now lets make some real tire objects from those
tires = [Tire.fromDescription(each) for each in descriptions]
#make sure they still print
[print(each.description) for each in tires]
print('original sort')
[print(each.description) for each in sorted(tires, key = attrgetter('radius'))]
print('reversed original sort')
[print(each.description) for each in sorted(tires, key = attrgetter('radius'), reverse = True)]
print('width sort')
[print(each.description) for each in sorted(tires, key = attrgetter('width'), reverse = True)]
print('radius>>width>>profile sort')
[print(each.description) for each in sorted(tires, key = attrgetter('radius', 'width', 'profile'))]
这种方法的价值希望在最后是显而易见的。我们预先付出更大的代价(就代码空间而言)来具体化轮胎对象。但是一旦有了,我们就可以开始疯狂地对它们进行各种排序。考虑到将字符串表示和所需的排序输出相结合的某些假设,最初提出的算法工作得很好。但是,如果您需要更改排序输出,根据最后一行(按字段 3、1、2 排序),那么方便的元组反向技巧将不再起作用。将“它是什么”与您将如何呈现(排序)分开会更好(IMO)。之后你可能会想到一些更聪明的事情来处理它们,而不仅仅是对它们进行排序。