#sort_list_tuples.py from math import sqrt #list of 2-tuples: (x,y) l1 = [(1,2),(6,0),(0,4),(12,4),(5,5),(12,3),(1,1)] #sort by x (default) then by y etc. print(sorted(l1)) #sort by y print(sorted(l1,key=lambda t: t[1])) #sort by sum print(sorted(l1,key=lambda t: t[0]+t[1])) #sort by distance from origin print(sorted(l1,key=lambda t: sqrt(t[0]**2+t[1]**2))) #sort by distance from a global point p p = (3,5) #must be global def dist_from_p(t): return sqrt((t[0]-p[0])**2 + (t[1]-p[1])**2) print(sorted(l1,key=dist_from_p)) #or: print(sorted(l1,key=lambda t: sqrt((t[0]-p[0])**2 + (t[1]-p[1])**2))) #list of 3-tuples: (x,y,z) l1 = [(1,2,0),(6,0,1),(0,4,1),(12,4,3),(5,4,2),(12,3,1),(3,3,5)] #sort by y then z print(sorted(l1,key=lambda t: (t[1],t[2]))) data = [('betty', 1),('bought', 1),('a', 1),('bit', 1),('of', 2), ('butter', 2),('but', 3),('the', 2),('was', 0),('bitter', 1)] #sort by number in reverse, then string print(sorted(data, key=lambda tup:(-tup[1], tup[0]))) #sort primarily by 0, then by index in a list of 1's values: suits = ['\u2663','\u2666','\u2665','\u2660'] hand = [(11, '♥'), (6, '♦'), (7, '♠'), (11, '♣'), (6, '♠')] print(sorted(hand,key=lambda t: (t[0], suits.index(t[1])))) #sort a list of strings by length of string l1 = ['ostrich','cat','mouse','ant', 'carp','elephant','zebra'] print(sorted(l1,key=lambda s: len(s))) l1 = ['ostrich','Cat','mouse','ant', 'carp','elephant','Zebra'] print(sorted(l1,key=lambda s: s.lower())) # ignore case # sort a string. returns list of chars s = "asdfBqweZrty" print(sorted(s, key=lambda c: c.lower())) #case-insensitive lst = [(1, 2), (2, 3, 1), (4,), (0, 3, 4)] #list of different-sized tuples print(sorted(lst)) #values order (first item of each tuple etc) print(sorted(lst,key=lambda t: len(t))) #sort by size of tuple print(sorted(lst,key=lambda t: (len(t),t))) #sort by size of tuple, then by values lst=[-4,3,-6,2,-2,5] print(sorted(lst,key=abs)) #use a built_in function ''' class record: def __init__(self,id,name,amount,measure): self.id = id self.name = name self.amount = amount self.measure = measure size = 10 list_records = [] for i in range(size): list_records.append(make_random_record()) #get this function #sort the list of records on id field: list_records_ordered = sorted(list_records,key=lambda rec: rec.id) '''