Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何打印列表中的项目,直到它们达到一定的行数_Python_Python 3.x - Fatal编程技术网

Python 如何打印列表中的项目,直到它们达到一定的行数

Python 如何打印列表中的项目,直到它们达到一定的行数,python,python-3.x,Python,Python 3.x,我正在做一个编码练习,你记不起一首歌的歌词,在打印出一定数量的诗句后,代码会打印“我放弃”。我需要创建代码来打印列表中的歌词,一行接一行,一次又一次,直到它达到一定数量的行,然后它打印“我放弃”。我陷入了困境,试图找出如何打印每个变量x行的数量,但我只找到了如何打印列表x次的数量 我已经知道了如何打印x个列表,但是我不知道如何只打印变量中的x行 lyrics = ["I wanna be your endgame", "I wanna be your first string",

我正在做一个编码练习,你记不起一首歌的歌词,在打印出一定数量的诗句后,代码会打印“我放弃”。我需要创建代码来打印列表中的歌词,一行接一行,一次又一次,直到它达到一定数量的行,然后它打印“我放弃”。我陷入了困境,试图找出如何打印每个变量x行的数量,但我只找到了如何打印列表x次的数量

我已经知道了如何打印x个列表,但是我不知道如何只打印变量中的x行

lyrics = ["I wanna be your endgame", "I wanna be your first string",
          "I wanna be your A-Team", "I wanna be your endgame, endgame"]

lines_of_sanity = 6

for x in range(lines_of_sanity):
    for i in (lyrics):
        print(i)
它将歌词的完整列表打印6次,但我需要它将列表中的元素打印6次,然后继续打印,直到诗句完成并打印(“我放弃”)

给定变量,正确的代码应为:

我想成为你的终局
我想成为你的第一根弦
我想成为你的A队
我想成为你的终局,终局
我想成为你的终局
我想成为你的第一根弦
我想成为你的A队
我想成为你的终局,终局
我放弃


你的意思是这样吗?对不起,如果这不是你的意思

lyrics = ["I wanna be your endgame", "I wanna be your first string",
      "I wanna be your A-Team", "I wanna be your endgame, endgame"]

lines_of_sanity = 6

for i in range(lines_of_sanity):
    print(lyrics[i%len(lyrics)])

print("I GIVE UP")
作为对你评论的回应,也许有人可以简化一下

for i in range(lines_of_sanity+len(lyrics)-(lines_of_sanity%len(lyrics))):
    print(lyrics[i%len(lyrics)])

print("I GIVE UP")

听起来你想重复完整的歌词,至少要打印一些行。因此,在本例中,您将打印两次完整的歌词。您可以使用以下公式计算数字:

times = math.ceil(6/len(lyrics)) 
有了它,一个很好的方法就是与一起使用。把它放在一起看起来像:

from itertools import chain, repeat
import math

lyrics = ["I wanna be your endgame", "I wanna be your first string",
          "I wanna be your A-Team", "I wanna be your endgame, endgame"]

lines_of_sanity = 6
times = math.ceil(lines_of_sanity/len(lyrics))

for l in chain.from_iterable(repeat(lyrics, times)):
    print(l)
print("I GIVE UP")

你能举个例子说明你希望输出的内容是什么吗?从描述中我并不完全清楚你需要它做什么。
对于i in(歌词):对于x in范围(理智的线条):print(i)
?这几乎正是我需要的。非常感谢。最后一部分是完成这首诗。所以对于这个变量,我需要加上“我想成为你的A队,我想成为你的终局,终局”来结束这首诗。有点像蟒蛇!