In [1]:
# 多行结果输出支持
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
In [88]:
import numpy as np
In [2]:
def fun(a, b, c, d):
print(a, b, c, d)
In [3]:
x = [1, 2, 3, 4]
In [9]:
fun(x)
In [15]:
fun(*x)
In [19]:
list(range(1, 5))
Out[19]:
In [24]:
st_end = (1, 5)
st_end1 = [1, 5]
In [25]:
list(range(*st_end))
list(range(*st_end1))
Out[25]:
Out[25]:
In [41]:
# A Python program to demonstrate use
# of packing
# This function uses packing to sum
# unknown number of arguments
# 变长参数
def mySum(*args):
sum = 0
for i in range(len(args)):
sum = sum + args[i]
return sum
In [ ]:
mySum(1, 2, 3, 4, 6, 7, 9)
mySum(1, 7, 9)
In [50]:
mySum(*st_end1)
mySum(*st_end)
Out[50]:
Out[50]:
In [51]:
# A sample program to demonstrate unpacking of
# dictionary items using **
def fun(a, b, c):
print(a, b, c)
In [56]:
# A call with unpacking of dictionary
d = {'a':2, 'b':4, 'c':10}
fun(*d)
fun(**d)
In [59]:
list1 = [2, 4, 5]
list2 = [3, 6, 2]
[*list1, *list2]
Out[59]:
In [60]:
dict1 = {'a': 2, 'b': 4}
dict2 = {'s': 3, 'b': 1, 'd': 5}
{**dict1, **dict2}
Out[60]:
In [65]:
set1 = set(list1)
set2 = set(list2)
set1
set2
Out[65]:
Out[65]:
In [66]:
{*set1, *set2}
Out[66]:
In [69]:
def my_function():
"""Do nothing, but document it.
No, really, it doesn't do anything.
"""
pass
print(my_function.__doc__)
In [73]:
aq = 'jiji'
a, c, d, f=aq
a,c, d,f
Out[73]:
In [77]:
aq = '你好我哈'
a, c, d, f=aq
a,c, d,f
Out[77]:
In [78]:
data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
_, shares, price, _ = data
In [79]:
shares, price
Out[79]:
In [89]:
# 去掉最高分和最低分计算平均成绩
def drop_first_last(grades):
first, *middle, last = grades
return np.mean(middle)
In [94]:
arg = [89, 78, 98, 36, 68, 74, 81]
drop_first_last(arg)
drop_first_last([89, 78, 98, 36, 68, 74, 81])
Out[94]:
Out[94]:
In [95]:
# 去掉最高分和最低分计算平均成绩
def drop_first_last1(*grades):
first, *middle, last = grades
return np.mean(middle)
In [100]:
drop_first_last1(*arg)
drop_first_last1(89, 78, 98, 36, 68, 74, 81)
Out[100]:
Out[100]:
In [106]:
record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
record1 = ('Dae', 'dae@example.com', '773-555-1212')
for t in [record, record1]:
name, email, *phone_numbers = t
print(name, email, phone_numbers)
In [108]:
*trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]
trailing
current
Out[108]:
Out[108]:
In [109]:
records = [
('foo', 1, 2),
('bar', 'hello'),
('foo', 3, 4),
]
def do_foo(x, y):
print('foo', x, y)
def do_bar(s):
print('bar', s)
for tag, *args in records:
if tag == 'foo':
do_foo(*args)
elif tag == 'bar':
do_bar(*args)
In [112]:
line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
uname, *fields, homedir, sh = line.split(':')
uname
homedir
sh
fields
Out[112]:
Out[112]:
Out[112]:
Out[112]:
In [115]:
record = ('ACME', 50, 123.45, (12, 18, 2012))
name, *_, (*_, year) = record
name
year
Out[115]:
Out[115]:
In [122]:
from collections import deque
q = deque(maxlen=3)
q.append(1)
q.append(2)
q.append(3)
q
Out[122]:
In [123]:
q.append(4)
q
Out[123]:
In [128]:
deque([2, 3, 4], maxlen=3)
q.append(5)
q
Out[128]:
Out[128]:
In [129]:
q.appendleft(9)
q
Out[129]:
In [130]:
q.pop()
Out[130]:
In [131]:
q
Out[131]:
In [132]:
q.popleft()
q
Out[132]:
Out[132]:
In [133]:
q.appendleft(5)
q
Out[133]:
In [134]:
q.append(4)
q
Out[134]:
In [136]:
import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
heapq.nlargest(3, nums)
heapq.nsmallest(3, nums)
Out[136]:
Out[136]:
In [137]:
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
# 使用price 进行比较
In [138]:
cheap
expensive
Out[138]:
Out[138]:
In [139]:
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
import heapq
heap = list(nums)
heapq.heapify(heap)
heap
Out[139]:
In [144]:
d = {
'a' : [1, 3, 3],
'b' : (4, 5)
}
e = {
'a' : {1, 2, 3},
'b' : {4, 5}
}
In [148]:
d['a']
Out[148]:
In [151]:
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(4)
d
Out[151]:
In [152]:
d = defaultdict(set)
d['a'].add(1)
d['a'].add(2)
d['b'].add(4)
In [155]:
d
d.values()
Out[155]:
Out[155]:
In [156]:
import json
In [157]:
from collections import OrderedDict
d = OrderedDict()
d['foo'] = 1
d['bar'] = 2
d['spam'] = 3
d['grok'] = 4
# Outputs "foo 1", "bar 2", "spam 3", "grok 4"
for key in d:
print(key, d[key])
In [158]:
json.dumps(d)
Out[158]:
In [159]:
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
In [162]:
prices.values()
prices.keys()
Out[162]:
Out[162]:
In [161]:
min(zip(prices.values(), prices.keys()))
max(zip(prices.values(), prices.keys()))
Out[161]:
Out[161]:
In [163]:
sorted(zip(prices.values(), prices.keys()))
Out[163]:
In [167]:
list(zip(prices.values(), prices.keys()))
Out[167]:
In [165]:
sorted(prices.items())
Out[165]:
In [168]:
a = {
'x' : 1,
'y' : 2,
'z' : 3
}
b = {
'w' : 10,
'x' : 11,
'y' : 2
}
In [177]:
# Find keys in common
a.keys() & b.keys() # 交集
# Find keys in a that are not in b
a.keys() - b.keys() # 补集
# Find (key,value) pairs in common
a.items() & b.items()
Out[177]:
Out[177]:
Out[177]:
In [178]:
# Make a new dictionary with certain keys removed
c = {key:a[key] for key in a.keys() - {'z', 'w'}}
c
Out[178]:
In [179]:
a.keys()|b.keys() # 并集
Out[179]:
In [180]:
a.keys()^b.keys() # 对称差集
Out[180]:
In [182]:
a = np.array([1, 3, 4, 6, 7, 1, 2, 8])
In [183]:
a
Out[183]:
In [185]:
s1 = slice(2, 6)
a[s1]
a[2:6]
Out[185]:
Out[185]:
In [193]:
b = [1, 5, 7, 9, 0, 2, 1, 45, 5]
s2 = slice(2, 6, 2)
b[s2]
del b[s2]
b
s2.start, s2.stop, s2.step
Out[193]:
Out[193]:
Out[193]:
In [200]:
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
from collections import Counter
word_counts = Counter(words)
# 出现频率最高的3个单词
top_three = word_counts.most_common(3)
top_three
word_counts
sorted(zip(word_counts.values(), word_counts.keys()), reverse=True)
Out[200]:
Out[200]:
Out[200]:
In [207]:
word_counts
# 增加1
word_counts.update(words)
word_counts
Out[207]:
Out[207]:
In [208]:
rows = [
{'fname': 'Brian', 'lname': 'Jones', 'uid': 1003},
{'fname': 'David', 'lname': 'Beazley', 'uid': 1002},
{'fname': 'John', 'lname': 'Cleese', 'uid': 1001},
{'fname': 'Big', 'lname': 'Jones', 'uid': 1004}
]
In [210]:
from operator import itemgetter
rows_by_fname = sorted(rows, key=itemgetter('fname'))
rows_by_uid = sorted(rows, key=itemgetter('uid'))
print(rows_by_fname)
In [211]:
print(rows_by_uid)
In [212]:
# itemgetter() 函数也支持多个 keys
rows_by_lfname = sorted(rows, key=itemgetter('lname','fname'))
print(rows_by_lfname)
In [213]:
min(rows, key=itemgetter('uid'))
Out[213]:
In [214]:
rows = [
{'address': '5412 N CLARK', 'date': '07/01/2012'},
{'address': '5148 N CLARK', 'date': '07/04/2012'},
{'address': '5800 E 58TH', 'date': '07/02/2012'},
{'address': '2122 N CLARK', 'date': '07/03/2012'},
{'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
{'address': '1060 W ADDISON', 'date': '07/02/2012'},
{'address': '4801 N BROADWAY', 'date': '07/01/2012'},
{'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
]
In [215]:
from operator import itemgetter
from itertools import groupby
# Sort by the desired field first
rows.sort(key=itemgetter('date'))
# Iterate in groups
for date, items in groupby(rows, key=itemgetter('date')):
print(date)
for i in items:
print(' ', i)
In [217]:
# 列表表达式
mylist = [1, 4, -5, 10, -7, 2, 3, -1]
[n for n in mylist if n > 0]
[n for n in mylist if n < 0]
Out[217]:
Out[217]:
In [220]:
# 生成器
pos = (n for n in mylist if n > 0)
pos
Out[220]:
In [221]:
next(pos)
Out[221]:
In [222]:
next(pos)
Out[222]:
In [223]:
list(pos)
Out[223]:
In [225]:
# 使用 filter 函数实现
values = ['1', '2', '-3', '-', '4', 'N/A', '5']
def is_int(val):
try:
x = int(val)
return True
except ValueError:
return False
list(filter(is_int, values))
Out[225]:
In [229]:
# 替换
[n if n > 0 else 0 for n in mylist]
Out[229]:
In [233]:
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
# Make a dictionary of all prices over 200
{key: value for key, value in prices.items() if value > 200}
# Make a dictionary of tech stocks
tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'}
{key: value for key, value in prices.items() if key in tech_names}
Out[233]:
Out[233]:
In [231]:
dict((key, value) for key, value in prices.items() if value > 200)
Out[231]:
In [236]:
nums = [1, 2, 3, 4, 5]
sum((x * x for x in nums)) # 显示的传递一个生成器表达式对象
sum(x * x for x in nums) # 更加优雅的实现方式,省略了括号
Out[236]:
Out[236]:
In [ ]: