gpt4 book ai didi

python 现在,接下来,n 次迭代

转载 作者:太空狗 更新时间:2023-10-29 22:11:42 27 4
gpt4 key购买 nike

编写一个可以迭代任何可迭代对象的通用函数,返回现在,下一对。

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

最佳答案

我的建议是,

from collections import deque

def now_nxt_deque(iterable, n=1):
deq = deque(maxlen=n)
for i in iterable:
deq.append(i)
if len(deq) == n:
yield tuple(deq)

for i in now_nxt_deque("hello world", 3):
print(i)

('h', 'e', 'l')
('e', 'l', 'l')
('l', 'l', 'o')
('l', 'o', ' ')
('o', ' ', 'w')
(' ', 'w', 'o')
('w', 'o', 'r')
('o', 'r', 'l')
('r', 'l', 'd')

关于python 现在,接下来,n 次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11164177/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com