编写一个通用函数,可以迭代任何现在返回的可迭代对象,下一组。
def now_nxt(iterable):
iterator = iter(iterable)
nxt = iterator.__next__()
for x in iterator:
now = nxt
nxt = x
yield (now,nxt)
for i in now_nxt("hello world"):
print(i)
('h', 'e')
('e', 'l')
('l', 'l')
('l', 'o')
('o', ' ')
(' ', 'w')
('w', 'o')
('o', 'r')
('r', 'l')
('l', 'd')
我一直在考虑编写一个可以设置每个元组中项目数的函数的最佳方法。
例如,如果它是
func("hello",n=3)
结果将是:
('h','e','l')
('e','l','l')
('l','l','o')
我是使用 timeit 的新手,所以请指出我在这里做错了什么:
import timeit
def n1(iterable, n=1):
#now_nxt_deque
from collections import deque
deq = deque(maxlen=n)
for i in iterable:
deq.append(i)
if len(deq) == n:
yield tuple(deq)
def n2(sequence, n=2):
# now_next
from itertools import tee
iterators = tee(iter(sequence), n)
for i, iterator in enumerate(iterators):
for j in range(i):
iterator.__next__()
return zip(*iterators)
def n3(gen, n=2):
from itertools import tee, islice
gens = tee(gen, n)
gens = list(gens)
for i, gen in enumerate(gens):
gens[i] = islice(gens[i], i, None)
return zip(*gens)
def prin(func):
for x in func:
yield x
string = "Lorem ipsum tellivizzle for sure ghetto, consectetuer adipiscing elit."
print("func 1: %f" %timeit.Timer("prin(n1(string, 5))", "from __main__ import n1, string, prin").timeit(100000))
print("func 2: %f" %timeit.Timer("prin(n2(string, 5))", "from __main__ import n2, string, prin").timeit(100000))
print("func 3: %f" %timeit.Timer("prin(n3(string, 5))", "from __main__ import n3, string, prin").timeit(100000))
结果:
$ py time_this_function.py
func 1: 0.163129
func 2: 2.383288
func 3: 1.908363