In [1]:
# 多行结果输出支持
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
In [74]:
import itertools
item = iter([1, 2, 3, 4])
In [3]:
item
Out[3]:
In [4]:
for i in item:
print(i)
In [5]:
def frange(start, stop, increment):
x = start
while x < stop:
yield x
x += increment
In [6]:
for i in frange(1, 19, 2):
print(i)
class Node:
def __init__(self, value):
self._value = value
self._children = []
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self, node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()
自定义迭代必须实现 __iter__
方法
__reversed__()
方法来实现反向迭代__reversed__()
的特殊方法时才能生效。 如果两者都不符合,那你必须先将对象转换为一个列表才行class Countdown:
def __init__(self, start):
self.start = start
# Forward iterator
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
# Reverse iterator
def __reversed__(self):
n = 1
while n <= self.start:
yield n
n += 1
for rr in reversed(Countdown(30)):
print(rr)
for rr in Countdown(30):
print(rr)
In [7]:
a = [1, 2, 3, 4]
for x in reversed(a):
print(x)
numba对numpy的大型数据进行加速, 小型数据的话,效果就不好了
In [40]:
import numba
@numba.jit
def sum2d(arr):
M, N = arr.shape
result = 0.0
for i in range(M):
for j in range(N):
result += arr[i,j]
return result
In [45]:
import numpy as np
xx = np.random.rand(4000, 4000) * 80000
In [46]:
sum2d(xx)
Out[46]:
In [49]:
def count(n):
while True:
yield n
n += 1
In [50]:
c = count(0)
In [51]:
# Now using islice()
import itertools
for x in itertools.islice(c, 10, 20):
print(x)
In [53]:
items = ['a', 'b', 'c']
from itertools import permutations
for p in permutations(items):
print(p)
In [54]:
# 指定长度的所有排列
for p in permutations(items, 2):
print(p)
In [59]:
list(permutations(range(4), 2))
Out[59]:
In [61]:
from itertools import combinations
for c in combinations(items, 3):
print(c)
In [62]:
for c in combinations(items, 2):
print(c)
In [63]:
for c in combinations(items, 1):
print(c)
In [64]:
for c in combinations(range(5), 2):
print(c)
In [67]:
from itertools import combinations_with_replacement
for c in combinations_with_replacement(items, 3):
print(c)
In [70]:
from itertools import chain
a = [1, 2, 3, 4]
b = ['x', 'y', 'z']
# 迭代完 a 再迭代 b
for x in chain(a, b):
print(x)
In [73]:
a = [1, 2, 3, 4]
b = ('x', 'y', 'z')
# 迭代完 a 再迭代 b
# 只要 a,b 是可迭代的就行
for x in chain(a, b):
print(x)
In [76]:
from collections import Iterable
def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x)
else:
yield x
items = [1, 2, [3, 4, [5, 6], 7], 8]
for x in flatten(items):
print(x)
iter 函数一个鲜为人知的特性是它接受一个可选的 callable 对象和一个标记(结尾)值作为输入参数。 当以这种方式使用的时候,它会创建一个迭代器, 这个迭代器会不断调用 callable 对象直到返回值和标记值相等为止
In [ ]: