Skip to content

Instantly share code, notes, and snippets.

@spinupol
Created September 22, 2015 21:25
Show Gist options
  • Save spinupol/a34442e50d2fa8895a15 to your computer and use it in GitHub Desktop.
Save spinupol/a34442e50d2fa8895a15 to your computer and use it in GitHub Desktop.
Python snippets
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"empty\n"
]
}
],
"source": [
"# Check if list is empty\n",
"li=[]\n",
"\n",
"if not li:\n",
" print 'empty'"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0000012345\n",
"000123.456\n"
]
}
],
"source": [
"# left padding zeros for readability\n",
"print \"12345\".zfill(10)\n",
"print str(123.456).zfill(10)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'a': 1, 'b': 10, 'c': 11}"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# merging two dictionaries (b 10 should overwrite b 2)\n",
"x = {'a':1, 'b': 2}\n",
"y = {'b':10, 'c': 11}\n",
"z = dict(x.items() + y.items())\n",
"z"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, [4, 5]]\n",
"[1, 2, 3, 4, 5]\n"
]
}
],
"source": [
"# append vs extend\n",
"x = [1, 2, 3]\n",
"x.append([4, 5])\n",
"print (x)\n",
"\n",
"x = [1, 2, 3]\n",
"x.extend([4, 5])\n",
"print (x)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"pizza\n"
]
}
],
"source": [
"# list to dictionary using enumerate\n",
"choices = ['pizza', 'pasta', 'salad', 'nachos']\n",
"x =list(enumerate(choices))\n",
"x\n",
"print x[0][0]\n",
"print x[0][1]"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 a\n",
"1 b\n",
"2 c\n",
"3 d\n"
]
}
],
"source": [
"# enumerate example 2\n",
"mylist = [\"a\",\"b\",\"c\",\"d\"]\n",
"for i,j in enumerate(mylist):\n",
" print i,j"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]\n"
]
}
],
"source": [
"# slicing\n",
"a= range(0,10)\n",
"b=a[0:10]\n",
"c=a[0:] \n",
"d=a[:10] \n",
"e=a[:]\n",
"f=a[::-1]\n",
"print a\n",
"print b\n",
"print c\n",
"print d\n",
"print e\n",
"print f"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"deque([1, 2, 3, 4, 5])\n",
"deque([5, 1, 2, 3, 4])\n",
"deque([3, 4, 5, 1, 2])\n",
"deque([4, 5, 1, 2, 3])\n"
]
}
],
"source": [
"#circular list and circular movement\n",
"import collections\n",
"l = collections.deque([1,2,3,4,5])\n",
"l.rotate(0)\n",
"print l\n",
"l.rotate(1)\n",
"print l\n",
"l.rotate(2)\n",
"print l\n",
"l.rotate(-1)\n",
"print l"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],\n",
" [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],\n",
" [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],\n",
" [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],\n",
" [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],\n",
" [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],\n",
" [70, 71, 72, 73, 74]]\n"
]
}
],
"source": [
"#produce even chunks of data\n",
"def chunks(l, n):\n",
" \"\"\"Yield successive n-sized chunks from l.\"\"\"\n",
" for i in xrange(0, len(l), n):\n",
" yield l[i:i+n]\n",
"\n",
"import pprint\n",
"pprint.pprint(list(chunks(range(10, 75), 10)))"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
]
}
],
"source": [
"# merging mutiple lists into 1\n",
"l = [[1,2,3],[4,5,6], [7], [8,9]]\n",
"ll=sum(l, [])\n",
"print ll\n",
"lll=reduce(lambda x,y: x+y,l)\n",
"print lll"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"c\n"
]
}
],
"source": [
"# random selection from a list\n",
"import random\n",
"foo = ['a', 'b', 'c', 'd', 'e']\n",
"print(random.choice(foo))"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[{'age': 100, 'name': 'Bart'}, {'age': 39, 'name': 'Homer'}]\n",
"[{'age': 39, 'name': 'Homer'}, {'age': 100, 'name': 'Bart'}]\n"
]
}
],
"source": [
"# sort dictionary by value instead of key\n",
"c =[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':100}]\n",
"newlist = sorted(c, key=lambda k: k['name'])\n",
"print newlist\n",
"newlist = sorted(c, key=lambda k: k['age'])\n",
"print newlist"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "SyntaxError",
"evalue": "invalid syntax (<ipython-input-14-b7781d56cd36>, line 4)",
"output_type": "error",
"traceback": [
"\u001b[1;36m File \u001b[1;32m\"<ipython-input-14-b7781d56cd36>\"\u001b[1;36m, line \u001b[1;32m4\u001b[0m\n\u001b[1;33m or\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
]
}
],
"source": [
"#copying a file in python\n",
"import shutil\n",
"shutil.copy2('/dir/file.ext', '/new/dir')\n",
"or\n",
"copyfile(src, dst)"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#switch statement in python\n",
"def f(x):\n",
" return {\n",
" 'a': 1,\n",
" 'b': 2,\n",
" }.get(x, 9) # 9 is default if x not found"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<type 'dict'>\n",
"<type 'list'>\n"
]
}
],
"source": [
"#determine type of an object\n",
"type([]) is list\n",
"type({}) is dict\n",
"type('') is str\n",
"type(0) is int\n",
"print type({})\n",
"print type([])"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Chained comparison operators work! \n",
"Chained comparison operators work! \n",
"Chained comparison operators work! \n",
"\n"
]
}
],
"source": [
"#chained comaprison\n",
"mynumber = 3\n",
"\n",
"if 4 > mynumber > 2:\n",
" print(\"Chained comparison operators work! \\n\" * 3)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"height missing?\n",
"\n"
]
}
],
"source": [
"# dict default if key missing\n",
"my_dict = {'name': 'Lancelot', 'quest': 'Holy Grail', 'favourite_color': 'blue'}\n",
"print(my_dict.get('height', 'height missing?\\n'))"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('quest', 'Holy Grail')\n",
"('name', 'Lancelot')\n",
"('favourite_color', 'blue')\n"
]
}
],
"source": [
"# dict iter items, similar to enumerate for lists\n",
"for key, value in my_dict.iteritems():\n",
" print(key, value)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'even'"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# ternary operator\n",
"b = 4\n",
"x = 'odd' if b%2 ==1 else 'even'\n",
"x"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['a', 'b', 'd']\n",
"['b', 'd']\n"
]
}
],
"source": [
"#pop usage\n",
"a = ['a', 'b', 'c', 'd']\n",
"a.pop(-2)\n",
"print a\n",
"a.pop(0)\n",
"print a"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['alabaster==0.7.3',\n",
" 'argcomplete==0.8.9',\n",
" 'astropy==1.0.3',\n",
" 'babel==1.3',\n",
" 'backports.ssl-match-hostname==3.4.0.2',\n",
" 'bcolz==0.9.0',\n",
" 'beautifulsoup4==4.3.2',\n",
" 'binstar==0.11.0',\n",
" 'bitarray==0.8.1',\n",
" 'blaze==0.8.0',\n",
" 'blz==0.6.2',\n",
" 'bokeh==0.9.0',\n",
" 'boto==2.38.0',\n",
" 'bottleneck==1.0.0',\n",
" 'cdecimal==2.3',\n",
" 'certifi==14.5.14',\n",
" 'cffi==1.1.0',\n",
" 'clyent==0.3.4',\n",
" 'colorama==0.3.3',\n",
" 'conda-build==1.14.1',\n",
" 'conda-env==2.4.2',\n",
" 'conda==3.16.0',\n",
" 'configobj==5.0.6',\n",
" 'cryptography==0.9.1',\n",
" 'cython==0.22.1',\n",
" 'cytoolz==0.7.3',\n",
" 'datashape==0.4.5',\n",
" 'decorator==3.4.2',\n",
" 'docutils==0.12',\n",
" 'enum34==1.0.4',\n",
" 'fastcache==1.0.2',\n",
" 'flask==0.10.1',\n",
" 'funcsigs==0.4',\n",
" 'future==0.15.0',\n",
" 'gevent-websocket==0.9.3',\n",
" 'gevent==1.0.1',\n",
" 'greenlet==0.4.7',\n",
" 'grin==1.2.1',\n",
" 'h5py==2.5.0',\n",
" 'idna==2.0',\n",
" 'ipaddress==1.0.7',\n",
" 'ipython==3.2.1',\n",
" 'itsdangerous==0.24',\n",
" 'jdcal==1.0',\n",
" 'jedi==0.8.1',\n",
" 'jinja2==2.8',\n",
" 'jsonschema==2.4.0',\n",
" 'llvmlite==0.5.0',\n",
" 'lxml==3.4.4',\n",
" 'markupsafe==0.23',\n",
" 'matplotlib==1.4.3',\n",
" 'menuinst==1.0.4',\n",
" 'mistune==0.7',\n",
" 'mock==1.0.1',\n",
" 'multipledispatch==0.4.7',\n",
" 'networkx==1.9.1',\n",
" 'nltk==3.0.3',\n",
" 'nose==1.3.7',\n",
" 'numba==0.19.1',\n",
" 'numexpr==2.4.3',\n",
" 'numpy==1.9.2',\n",
" 'odo==0.3.2',\n",
" 'openpyxl==1.8.5',\n",
" 'pandas==0.16.2',\n",
" 'patsy==0.3.0',\n",
" 'pep8==1.6.2',\n",
" 'pillow==2.8.2',\n",
" 'pip==7.1.2',\n",
" 'ply==3.6',\n",
" 'psutil==2.2.1',\n",
" 'py==1.4.27',\n",
" 'pyaml==15.8.2',\n",
" 'pyasn1==0.1.7',\n",
" 'pycosat==0.6.1',\n",
" 'pycparser==2.14',\n",
" 'pycrypto==2.6.1',\n",
" 'pyexcel-io==0.0.6',\n",
" 'pyexcel-xls==0.0.7',\n",
" 'pyexcel==0.1.7',\n",
" 'pyflakes==0.9.2',\n",
" 'pygments==2.0.2',\n",
" 'pyopenssl==0.15.1',\n",
" 'pyparsing==2.0.3',\n",
" 'pyreadline==2.0',\n",
" 'pytest==2.7.1',\n",
" 'python-dateutil==2.4.2',\n",
" 'pytz==2015.4',\n",
" 'pywin32==219',\n",
" 'pyyaml==3.11',\n",
" 'pyzmq==14.7.0',\n",
" 'requests==2.7.0',\n",
" 'rope==0.9.4',\n",
" 'runipy==0.1.3',\n",
" 'scikit-image==0.11.3',\n",
" 'scikit-learn==0.16.1',\n",
" 'scipy==0.15.1',\n",
" 'selenium==2.47.1',\n",
" 'setuptools==18.1',\n",
" 'six==1.9.0',\n",
" 'snowballstemmer==1.2.0',\n",
" 'sockjs-tornado==1.0.1',\n",
" 'sphinx-rtd-theme==0.1.7',\n",
" 'sphinx==1.3.1',\n",
" 'spyder==2.3.5.2',\n",
" 'sqlalchemy==1.0.5',\n",
" 'statsmodels==0.6.1',\n",
" 'sympy==0.7.6',\n",
" 'tables==3.2.0',\n",
" 'texttable==0.8.3',\n",
" 'toolz==0.7.2',\n",
" 'tornado==4.2.1',\n",
" 'ujson==1.33',\n",
" 'unicodecsv==0.9.4',\n",
" 'werkzeug==0.10.4',\n",
" 'wheel==0.24.0',\n",
" 'xlrd==0.9.3',\n",
" 'xlsxwriter==0.7.3',\n",
" 'xlwings==0.3.5',\n",
" 'xlwt-future==0.8.0',\n",
" 'xlwt==1.0.0']"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#get a list of all librarires installed\n",
"import pip\n",
"sorted([\"%s==%s\" % (i.key, i.version) for i in pip.get_installed_distributions()])"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#clear screen\n",
"import os\n",
"os.system('cls')\n",
"#os.system('clear') in unix"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"empty\n",
"0000012345\n"
]
}
],
"source": [
"#run python program from python shell\n",
"import os;execfile('C:\\Users\\Pinupols\\Desktop\\py_code\\onetime.py')"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3 1 6 [1, 2, 3]\n",
"set([2, 3])\n",
"set([1, 2, 3, 4])\n",
"set([4])\n",
"set([1, 4])\n"
]
}
],
"source": [
"#set operations\n",
"#from sets import Set\n",
"s= [1,2,3]\n",
"t= [2,3,4]\n",
"print max(s),min(s),sum(s),sorted(s)\n",
"print set(s).intersection(t)\n",
"print set(s).union(t)\n",
"print set(t)-set(s)\n",
"print set(s).symmetric_difference(t)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.10"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment