In [1]:
# 多行结果输出支持
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
In [6]:
# 过滤器
fibonacci = [0,1,1,2,3,5,8,13,21,34,55]
list(filter(lambda x: x % 2, fibonacci))
Out[6]:
In [11]:
import functools
functools.reduce(lambda x,y: x+y, [47,11,42,67])
Out[11]:
# 读
# gzip compression
import gzip
with gzip.open('somefile.gz', 'rt') as f:
text = f.read()
# bz2 compression
import bz2
with bz2.open('somefile.bz2', 'rt') as f:
text = f.read()
# 写
# gzip compression
import gzip
with gzip.open('somefile.gz', 'wt') as f:
f.write(text)
# bz2 compression
import bz2
with bz2.open('somefile.bz2', 'wt') as f:
f.write(text)
import csv
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for row in f_csv:
# Process row
...
from collections import namedtuple
with open('stock.csv') as f:
f_csv = csv.reader(f)
headings = next(f_csv)
Row = namedtuple('Row', headings)
for r in f_csv:
row = Row(*r)
# Process row
...
In [13]:
import json
data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}
json_str = json.dumps(data)
In [14]:
json_str
Out[14]:
In [15]:
data = json.loads(json_str)
In [16]:
data
Out[16]:
# Writing JSON data
with open('data.json', 'w') as f:
json.dump(data, f)
# Reading data back
with open('data.json', 'r') as f:
data = json.load(f)
In [17]:
d = {'a': True,
'b': 'Hello',
'c': None}
json.dumps(d)
Out[17]:
In [ ]: