我有一个字符串列表,我需要创建一个函数,该函数每次运行时都会打印出列表的n个元素。
例如:
book1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o']
如果是n = 5
,我第一次运行该函数的预期输出是:a
b
c
d
e
第二次:f
g
h
i
j
我尝试了这个:def print_book(book):
printed = book
while printed != []:
for i in range(0, len(book), 5):
new_list = (book[i:i+5])
for el in new_list:
print(el)
break
del(printed[i:i+10])
然后,我要么打印出整个列表,要么每次运行该函数时都打印出前n个元素。如果已经问过这个问题,请向我指出,我真的很感激。谢谢!
最佳答案
我猜你可以尝试以下应用于迭代器book
的用户功能
def print_book(book):
cnt = 0
while cnt < 5:
try:
print(next(book))
except StopIteration:
print("You have reached the end!")
break
cnt += 1
这样>>> bk1 = iter(book1)
>>> print_book(bk1)
a
b
c
d
e
>>> print_book(bk1)
f
g
h
i
j
>>> print_book(bk1)
k
l
m
n
o
>>> print_book(bk1)
You have reached the end!
关于python - 每次运行函数时,打印出列表的n个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65544645/