Skip to content

Instantly share code, notes, and snippets.

@capttwinky
Created September 27, 2011 16:11
Show Gist options
  • Save capttwinky/1245494 to your computer and use it in GitHub Desktop.
Save capttwinky/1245494 to your computer and use it in GitHub Desktop.
example of lambdas in sorts
def main():
lstIn = "dog,horse,cat,trouser,shark,artichoke,constantine,Christmas,Antartica,Ninja,Sanitizer".split(",")
lst1 = sorted(lstIn) #looks ok, but sorts on ord(c)
print lst1 #uppers before lowers
lst2 = sorted(lstIn, key=lambda x: x.lower()) #does a case insenstive sort
print lst2 #what you'd expect from an alphabetic sort
lstIn.sort(key=lambda x: (len(x),lst2.index(x))) #to sort on n vars, return an n-tupple
print lstIn #list sorted by length of word then alphabet
return 0
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment