零、Prepare Jupyter notebook
- 安装配置虚拟环境
$ pip install virtuanlenv
$ virtualenv ENV
$ cd ENV
$ source bin/activate
$ pip install jupyter
$ jupyter notebook
- Jupyter notebook
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, machine learning and much more.
一、Practice makes perfect
"Flat is better than nested" - The Zen of Python
##Looping over a range of numbers
for i in range(6):
print(i**2)
##Looping over a collection
colors = ['red', 'green', 'blue', 'yellow']
for color in colors:
print (color)
##Looping over a collection
for i in range(len(colors)):
print (colors[i])
##Looping backwards
for color in reversed(colors):
print(color)
##Looping over a collection and indices
for i, color in enumerate(colors):
print(i, '-->', color)
##Looping over two collections
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue', 'yellow']
for name, color in zip(names, colors):
print(name,'-->','color')
##Looping in sorted order
colors = ['red', 'green', 'blue', 'yellow']
for color in sorted(colors):
print(color)
for color in sorted(colors, reverse=True):
print(color)
##Custom Sort Order
print(sorted(colors, key=len))
##Call a function until a sentinel value
blocks = []
while True:
block = f.read(32)
if block == '':
break
blocks.apeend(block)
##Better
blocks=[]
for block in iter(partial(f.read, 32),''):
blocks.append(block)
##Distinguishing multiple exit points in loops
def find(seq, target):
found = False
for i, value in enumerate(seq):
if value == target:
found =True
break
if not found:
return -1
return i
## Better
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else: ##Inside of every for loop is an else.
return -1
return i
##Looping over dictionary keys
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
for k in d:
print(k)
for k in d:
print(k,'-->',d[k])
for k, v in d.items(): ## Makes a hug list
print(k,'-->',v)
##Construct a dictionary from pairs
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue']
d = dict(zip(names, colors))
##Counting with dictionaries
colors = ['red', 'green', 'red', 'blue', 'green', 'red']
d = {}
for color in colors:
if color not in d:
d[color] = 0
d[color] +=1
##Better
x = {}
for color in colors:
x[color] = x.get(color,0) + 1
##Grouping with dictionaries
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
##group by name,length
d = {}
for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)
x = {}
for name in names:
key = len(name)
x.setdefault(key,[]).append(name)
##Better
from collections import defaultdict
d = defaultdict(list)
for name in names:
key = len(name)
d[key].append(name)
##Is a dictionary popitem() atomic?
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
while d:
key,value = d.popitem()
print(key,'-->',value)
##List Comprehensions and Generator Expressions
result = []
for i in range(10):
s = i**2
result.append(s)
print(sum(result))
##Better
print(sum(i**2 for i in range(10)))
##How to open and close files
f = open('data.txt')
try:
data = f.read()
finally:
f.close()
## Better
with open('data.txt') as f:
data = f.read()
##Using decorators to factor-out administrative logic
def web_lookup(url, saved={}):
if url in saved:
return saved[url]
page = urllib.urlopen(url).read()
saved[url] = page
return page
##Better
def cache(*arg):
pass
@cache
def web_lookup(url):
return urllib.urlopen(url).read()
##Concatenating strings
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
s = names[0]
for name in names[1:]:
s += ','+name
print(s)
##Better
print(','.join(names))
二、Reference
1)github:https://gist.github.com/JeffPaine/6213790
2)youtube:https://www.youtube.com/watch?v=OSGv2VnC0go&t=1253s
3)https://dev.to/dawranliou/never-write-for-loops-again