我想要类似的东西(如果从2
开始):
2, 3, ..., n-1, n, n-1, ..., 3, 2, 1, 0, 1, 2, 3, ... (forever)
有什么比这更简单的吗?:
def print_numbers_forth_and_back_forever(first_number, upper_limit):
for i in range(first_number, upper_limit):
print(i)
while True:
# back from n to 0
for i in reversed(range(0, upper_limit+1)):
print(i)
# 1 to n-1
for i in range(1, upper_limit):
print(i)
print_numbers_forth_and_back_forever(4, 10)
以下使用itertools
的将提供应满足要求的生成器-只需更改range(a, b)
的参数即可更改输出:
from itertools import cycle, chain
r = range(10)
r_reversed = reversed(r[1:-1])
gen = cycle(chain(r, r_reversed))
输出:
>>> from itertools import islice
>>> list(islice(gen, 20))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1]
要以任意整数开始,请对start
使用islice
自变量,如下所示:
>>> list(islice(gen, 4, 20))
[4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1]
与您使用生成器相同:
# you can add start argument to replace 0
def gen_infinite_bounce(first, end) :
yield from range(first,end)
while True:
yield from range(end, 0, -1)
yield from range(0, end)
first = 2 # first Value
end = 5 # end bounce
# you can create a variable start to replace 0
for i in gen_infinite_bounce(first, end):
print(i)
您也可以使用itertools:
first = 2 # first Value
end = 5 # end bounce
# you can create a variable start to replace 0
from itertools, import chain, cycle
for i in chain(
range(start, end), cycle(
chain(
range(end, 0, -1),
range(0, end)
)
)
):
print(i)
您可以将itertools
与range()
对象一起使用,以有效地创建所需的输出:
from itertools import cycle, chain, islice
def cycle_fwd_back(first, last):
yield from range(first, last)
yield from cycle(chain(reversed(range(last + 1)), range(1, last)))
# First 30
print(list(islice(cycle_fwd_back(4, 10), 30)))
输出:
[4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7]
您可以使用下面的代码
def print_numbers_forth_and_back_forever(first_number, upper_limit):
inc =
i = first_number
while True:
if i == upper_limit:
inc = -1
elif i == 0:
inc = 1
print(i,end = ' ')
i += inc