In [1]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from pandas import DataFrame, Series
from numpy.random import randn
In [2]:
a = 'this is a string'
b = 'this is another string'
a + b
Out[2]:
In [3]:
template = '%.2f %s are worth $%d'
template % (4.5560, 'Argentine Pesos', 1)
Out[3]:
In [4]:
template % (3.3333, a + b, 2)
Out[4]:
In [5]:
True and True
Out[5]:
In [6]:
False or True
Out[6]:
In [7]:
a = [1, 2, 3]
if a:
print 'I found something'
In [8]:
b = []
if not b:
print 'Empty!'
In [9]:
bool([]), bool([1, 2, 3])
Out[9]:
In [10]:
bool('Hello world!'), bool('')
Out[10]:
In [11]:
bool(0), bool(1)
Out[11]:
In [12]:
s = '3.14159'
fval = float(s)
type(fval)
Out[12]:
In [13]:
int(fval)
Out[13]:
In [14]:
bool(fval)
Out[14]:
In [15]:
bool(0)
Out[15]:
In [16]:
a = None
a is None
Out[16]:
In [17]:
b = 5
b is not None
Out[17]:
In [18]:
def add_and_maybe_multiply(a, b, c=None):
result = a + b
if c is not None:
result = result * c
return result
In [20]:
from datetime import datetime, date, time
dt = datetime(2011, 10, 29, 20, 30, 21)
dt.day
Out[20]:
In [21]:
dt.minute
Out[21]:
In [22]:
dt.date()
Out[22]:
In [23]:
dt.time()
Out[23]:
In [24]:
dt.strftime('%m/%d/%Y %H:%M')
Out[24]:
In [25]:
datetime.strptime('20091031', '%Y%m%d')
Out[25]:
In [26]:
dt.replace(minute=0, second=0)
Out[26]:
In [28]:
dt2 = datetime(2011, 11, 15, 22, 30)
delta = dt2 - dt
delta
Out[28]:
In [29]:
type(delta)
Out[29]:
In [30]:
dt
Out[30]:
In [31]:
dt + delta
Out[31]:
In [32]:
x=-1
In [33]:
if x < 0:
print 'It"s negative'
In [34]:
def px(x):
if x < 0:
print 'It"s negative'
elif x == 0:
print 'Equal to zero'
elif 0 < x < 5:
print 'Positive but smaller than 5'
else:
print 'Positive and larger than or equal to 5'
In [35]:
px(x)
In [36]:
px(3)
In [37]:
px(10)
In [38]:
px(0)
In [40]:
a = 5; b = 7
c = 8; d = 4
if a < b or c > d:
print 'Made it'
In [41]:
def mysum(seq):
total = 0
for value in seq:
if value is None:
continue
total += value
return total
In [42]:
mysum([1, 2, None, 4, None, 5])
Out[42]:
In [44]:
def mysum5(seq):
total_until_5 = 0
for value in seq:
if value == 5:
break
total_until_5 += value
return total_until_5
In [45]:
mysum5([1, 2, 0, 4, 6, 5, 2, 1])
Out[45]:
In [46]:
x = 256
total = 0
while x > 0:
if total > 500:
break
total += x
x = x // 2
In [47]:
total
Out[47]:
In [48]:
def f(x, y, z):
# TODO: 实现这个函数!
pass
In [49]:
float('1.2345')
Out[49]:
In [50]:
float('som')
In [55]:
def attempt_float(x):
try:
return float(x)
except ValueError:
return x
In [52]:
attempt_float('1.2345')
Out[52]:
In [53]:
attempt_float('som')
Out[53]:
In [54]:
float(1, 2)
In [56]:
attempt_float((1, 2))
In [57]:
def attempt_float(x):
try:
return float(x)
except (TypeError, ValueError):
return x
In [58]:
f = open('ch13testfinally.txt', 'w')
try:
f.write("akakakak")
finally:
f.close()
In [59]:
!cat ch13testfinally.txt
In [60]:
f = open('ch13else.txt', 'w')
try:
f.write('bkbkbkbkbk')
except:
print 'Failed'
else:
print 'Succeeded'
finally:
f.close()
In [61]:
!cat ch13else.txt
In [62]:
range(10)
Out[62]:
In [63]:
range(0, 20, 2)
Out[63]:
In [65]:
val = 0
seq = [1, 2, 3, 4]
for i in range(len(seq)):
val += seq[i]
val
Out[65]:
In [66]:
sum = 0
for i in xrange(10000):
# %是求模运算符
if i % 3 == 0 or i % 5 == 0:
sum += i
sum
Out[66]:
In [67]:
x = 5
'Non-negative' if x >= 0 else 'Negative'
Out[67]:
In [68]:
tup = 4, 5, 6
tup
Out[68]:
In [69]:
nested_tup = (4, 5, 6), (7, 8)
nested_tup
Out[69]:
In [70]:
tuple([4, 0, 2])
Out[70]:
In [72]:
tup = tuple('string')
tup
Out[72]:
In [73]:
tup[0]
Out[73]:
In [74]:
tup = tuple(['foo', [1, 2], True])
tup[2] = False
In [75]:
tup[1].append(3)
tup
Out[75]:
In [76]:
(4, None, 'foo') + (6, 0) + ('bar',)
Out[76]:
In [77]:
('foo', 'bar') * 4
Out[77]:
In [78]:
tup = (4, 5, 6)
a, b, c = tup
In [79]:
b
Out[79]:
In [80]:
tup = 4, 5, (6, 7)
a, b, (c, d) = tup
d
Out[80]:
In [82]:
b, a = a, b
b
Out[82]:
In [83]:
seq = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
for a, b, c in seq:
pass
In [85]:
a = (1, 2, 2, 2, 3, 4, 2)
a.count(2)
Out[85]:
In [88]:
for x in a:
print str(x) + ','
In [89]:
a_list = [2, 3, 7, None]
tup = ('foo', 'bar', 'baz')
b_list = list(tup)
b_list
Out[89]:
In [90]:
b_list[1] = 'peekaboo'
b_list
Out[90]:
In [91]:
b_list.append('dwarf')
b_list
Out[91]:
In [95]:
tup + ('x',)
Out[95]:
In [96]:
b_list.insert(1, 'red')
b_list
Out[96]:
In [97]:
b_list.pop(2)
Out[97]:
In [98]:
b_list
Out[98]:
In [99]:
b_list.append('foo')
b_list.remove('foo')
b_list
Out[99]:
In [100]:
'dwarf' in b_list
Out[100]:
In [102]:
[4, None, 'foo'] + [7, 8, (2, 3)] + ['x']
Out[102]:
In [103]:
x = [4, None, 'foo']
x.extend([7, 8, (2, 3)])
Out[103]:
In [104]:
everything = []
for chunk in [b_list, x]:
everything.extend(chunk)
everything
Out[104]:
In [106]:
everything = []
for chunk in [b_list, x]:
everything = everything + chunk
everything
Out[106]:
In [107]:
a = [7, 2, 5, 1, 3]
a.sort()
a
Out[107]:
In [108]:
b = ['saw', 'small', 'He', 'foxes', 'six']
b.sort(key=len)
b
Out[108]:
In [109]:
import bisect
c = [1, 2, 2, 2, 3, 4, 7]
bisect.bisect(c, 2)
Out[109]:
In [110]:
bisect.bisect(c, 5)
Out[110]:
In [113]:
bisect.insort(c, 6)
c
Out[113]:
In [114]:
seq = [7, 2, 3, 7, 5, 6, 0, 1]
seq[1:5]
Out[114]:
In [116]:
seq[3:4] = [6, 3]
seq
Out[116]:
In [117]:
seq[:5]
Out[117]:
In [118]:
seq[3:]
Out[118]:
In [119]:
seq[-4:]
Out[119]:
In [120]:
seq[-6:-2]
Out[120]:
In [121]:
seq[::2]
Out[121]:
In [122]:
seq[::-1]
Out[122]:
In [123]:
for i, value in enumerate(seq):
print i, value
In [124]:
some_list = ['foo', 'bar', 'baz']
mapping = dict((v, i) for i, v in enumerate(some_list))
mapping
Out[124]:
In [ ]: