python - 每次运行函数时,打印出列表的n个元素

标签 python list for-loop

我有一个字符串列表,我需要创建一个函数,该函数每次运行时都会打印出列表的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/

相关文章:

python - 如何从2个同名的python文件中加载2个同名的函数?

python - 当我没有使用 @staticmethod 装饰器时,为什么我的减法函数在静态上下文中工作?

python - 在包含字符串和整数的列表上使用 max()

java - 如何将一个 HashMap 列表中的不同值添加到另一个 HashMap 列表

java - 移动 arraylist 对象的动画

c - C 中的 Brick-Breaker - 递增砖行问题

python - pandas 内存消耗 hdf 文件分组

python - 在 Python/SQLite 3 中格式化 SQL 查询输出

c# - 创建一个随机名称生成器。我该如何做到这一点?

algorithm - 在 VBA 中无故跳过循环