根据多个属性对列表进行排序?我有一份清单:[[12, 'tall', 'blue', 1],[2, 'short', 'red', 9],[4, 'tall', 'blue', 13]]如果我想按一个元素进行排序,比如说,高个子/矮个子元素,我可以通过s = sorted(s, key = itemgetter(1)).如果我想双管齐下高/矮和颜色,我可以做两次,每一个元素一次,但有更快的方法吗?
3 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
s = sorted(s, key = lambda x: (x[1], x[2]))
itemgetter
import operator s = sorted(s, key = operator.itemgetter(1, 2))
sort
sorted
s.sort(key = operator.itemgetter(1, 2))
一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
a = [('Al', 2),('Bill', 1),('Carol', 2), ('Abel', 3), ('Zeke', 2), ('Chris', 1)] b = sorted(sorted(a, key = lambda x : x[0]), key = lambda x : x[1], reverse = True) print(b) [('Abel', 3), ('Al', 2), ('Carol', 2), ('Zeke', 2), ('Bill', 1), ('Chris', 1)]
蝴蝶不菲
TA贡献1810条经验 获得超4个赞
list
tuple
def attr_sort(self, attrs=['someAttributeString']: '''helper to sort by the attributes named by strings of attrs in order''' return lambda k: [ getattr(k, attr) for attr in attrs ]
# would defined elsewhere but showing here for consisenessself.SortListA = ['attrA', 'attrB'] self.SortListB = ['attrC', 'attrA']records = .... #list of my objects to sortrecords.sort(key=self.attr_sort(attrs=self.SortListA)) # perhaps later nearby or in another functionmore_records = .... #another listmore_records.sort(key=self.attr_sort(attrs=self.SortListB))
object.attrA
object.attrB
object
object.attrC
object.attrA
.
添加回答
举报
0/150
提交
取消