Last modified: Aug, 2016
This page is for Python in general. There are also specific pages for numpy, scipy and matplotlib.
Use this
float("inf")
Below is an example of sorting a list of tuples by the 2nd item
>>> from operator import itemgetter
>>> data = [('a', 10),('b', 7),('c', 1), ('d',9)]
>>> sorted(data,key=itemgetter(1))
[('c', 1), ('b', 7), ('d', 9), ('a', 10)]
Reference:
A virtualenv environment will have access to global (system-level) Python packages outside but keep the local packages separately. So it is a good idea to minimize the installation of global packages for minimal dependency hell.
sudo apt-get install python-virtualenv # works on Ubuntu/Debian
virtualenv my_env
source my_env/bin/activate
After this, which python
and which pip
should give local Python and Pip instances.
virtualenv my_env
source my_env/Scripts/activate
pip install --upgrade pip
env/bin/pip install -r requirements.txt
Refer to Pip user guide and requirement file format for more information.
import urllib2
import simplejson
# Search Kickstarter with a keyword
url = 'http://www.kickstarter.com/projects/search.json?search=&term=USB'
res = urllib2.urlopen(url)
data = simplejson.load(res)
print data # will be a dictionary
This is such a good article that explained in an out of generators and keyword yield
in Python.
Another highly upvoted StackOverflow post on what Python generator is and what keyword yield
does.
Some “traps” below seem “naive” but caused lots of head-scratching
if key in dictionary:
but not this
if key in dictionary.keys():
because the latter will generate an intermediate array and can be very slow if the dictionary has lots of keys.