Python Reference Sheet
Reading from stdin
You can read from the standard input as follows
seq 10 | python -c 'import sys;print(sum([int(k) for k in sys.stdin.readlines()]))'
Reading History
import readline
for i in range(readline.get_current_history_length()):
print (readline.get_history_item(i + 1))
For some reason this isn’t working on my Windows 7 computer.
Update: it’s in ~/.python_history
. Open that as a text file.
No More Ugly Loops
No more of this ugliness (I used to write this way in my earlier posts in this blog)
for k in range(len(x)):
Instead, use enumerate
and zip
.
Enumerate
Enumerates a list.
x=[1,2,3]
for j,k in enumerate(x):
print(j,k)
Zip
Makes an iterator from two lists.
x=[1,2,3]
y=[4,5,6]
for j,k in zip(x,y):
print(j,k)
Reading Text
You don’t always have to save text files. Use StringIO.
from io import StringIO
s='''
COUNTRY,GDP (BILLIONS),CODE
Afghanistan,21.71,AFG
'''
df=pd.read_csv(StringIO(s))
case.. esac
Python does case statements differently.
# case statements in python