问题描述:

This prints the list correctly, but it prints it 7 times. I need to print my list only 2 times. I think the list is printing 7 times because there are 7 strings in the list.

Is there a way to only make it print my "custom" list a certain number of times? Because I want to use all these words, but on different lines, and vary each time they are used.

lyrics = ['Ring', 'Gering', 'ding', 'dingeringeding!', 'Wa', 'pa', 'pow!']

for y in lyrics:

print (lyrics[0] +' ' + (lyrics[2] + ' ') * 3 + lyrics[3])

网友答案:

use range, you have seven elements in your list so you iterate seven times with for y in lyrics:

for _ in range(2): # two iterations, prints two times
    print (lyrics[0] +' ' + (lyrics[2] + ' ') * 3 + lyrics[3])

It is probably nicer to use str.format:

for _ in range(2): # two iterations, prints two times
    print ("{} {} {}".format(lyrics[0] ,lyrics[2] * 3, lyrics[3] )

Which if you don't mind an extra newline can simply be multiplied:

In [36]:  print ("{} {} {}\n".format(lyrics[0] ,lyrics[2] * 3, lyrics[3] )* 2)
Ring dingdingding dingeringeding!
Ring dingdingding dingeringeding!
相关阅读:
Top