Created
November 4, 2011 11:16
-
-
Save bootandy/1339121 to your computer and use it in GitHub Desktop.
Python - lambdas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #-------------- Concept: Lambdas & string splits: -------------- | |
| TurnSpacesIntoColonsFunction = lambda x: '::'.join(x.split(" ")) | |
| NumberOfWordsFunction = lambda x: len(x.split(" ")) | |
| #-------------- Concept: lambdas inside a regex -------------- | |
| re.sub('[aeiou]', lambda match: match.group().upper()*3, 'abcdefghijklmnopqrstuvwxyz') | |
| #-------------- Concept: crazy function stacking with lambdas -------------- | |
| # d(c(b("some4 string 56 with 3numb3rs in"))) | |
| # -> totals up the numbers | |
| ### strip the characters replace with ' ' turn into a list | |
| b = lambda x: re.sub("\\D"," ", x).split(' ') | |
| ### filter out all the empty strings list elements | |
| c = lambda y: filter(lambda x: x, y) | |
| #### sum them | |
| d = lambda list: reduce(lambda x,y: int(x)+int(y), list) | |
| ###### an easier way to do it: | |
| reduce(lambda x,y : int(x) + int(y), re.findall("\\d","asdf23ds321")) | |
| ####### using reduce without lambdas: | |
| def value_of_word(): | |
| def count(i, a): | |
| return i + ord(a) - 64 | |
| return reduce(count, w, 0) | |
| ####### simple filters: | |
| def isMp3(s): | |
| if s.find(".mp3") == -1: | |
| return False | |
| else: | |
| return True | |
| list = ["1.mp3","2.txt", "3.mp3", "4.wmv","5.mp4" ] | |
| temp = filter(isMp3,list) | |
| ####### 3 interesting ways of doing the same thing string -> objectId mapping | |
| return map((lambda x: ObjectId(x)), list) | |
| return map(ObjectId, list) | |
| return [ObjectId(x) for x in list] | |
| ######## Lists: | |
| l = [1,2,3,4,5] | |
| l[1:] = [2, 3, 4, 5] | |
| l[2:] = [3, 4, 5] | |
| l[-2:] = [4, 5] | |
| l[::2] = [1, 3, 5] # Every 2nd value | |
| l[::-2] = [5, 3, 1] # Every 2nd value backwards | |
| # Rule: Python sequence slice addresses can be written as a[start:end:step] and any of start, stop or end can be dropped. a[::3] is every third element of the sequence. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment