[Python] Cheat sheet

alist = list(map(lambda x: x*x, [1, 5]))

# [1, 25]

alist = [2*i for i in range(4) if i%3 == 0]

# [0, 6]


Method Overloading

"""Unlike in Scala, you cannot just declare two methods with a same name."""
def some(arg="some_default_value"):
  if arg is None:
    print("Argument is empty")

Screen Shot 2014-11-24 at 5.19.53 PM


Python 3.3 Json documentation

To read JSON file from Python

def open_file(self):

config = json.loads(open(self.path).read())
self.title = config["title"]
self.artist = config["artist"]
self.timestamp = config["timestamp"]
self.track_id = config["track_id"]
self.tags = config["tags"]
self.similars = config["similars"]

except (OSError, IOError):
# blah blah

# In Python3, the data of self.title and others will be clean
# but in Python2 they will come like this u'value'

Multiple exceptions

except (one, two, three, ....) as e:

About sets

Screen Shot 2014-11-24 at 5.30.25 PMFind common and uncommon elements in a list (Bitwise operation)

a = [1,2,3,4]</pre>
<pre>b = [3,4,5,6]
list( set(a) & set(b) )    # [3,4]
list( set(a) ^ set(b) )    # [1,2,5,6]

Error handling when opening a file in Python

# IOError became an alias for OSError so having both of them
# will cover pretty much when your file name is not found.
# FileNotFoundError is not valid in Python3
except (OSError, IOError) as e:

Change default Python version in Mac

Actually you’d better not change it. Instead there is a way around for it. Make an alias!

nano ~/.bash_profile
// type in the following
alias py=python3
//Ctrl-O, Enter, Ctrl-x

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: