学习 Python 3 the Hard Way 第 40 课的课程。我正在尽我最大的努力来理解这个“for循环”是如何计算的。“对于 self.lyrics 中的行:打印(行)”我还想知道如何将“行”转换为数字,以便可以在歌词行顶部打印行号。我的轻微修改是添加另一行“你为什么脏老鼠”,看看它是否会按预期打印。我还删除了逗号,并按预期添加了该行class Song(): def __init__(self, lyrics): self.lyrics = lyrics---------------------------------------------------- def sing_me_a_song(self): for line in self.lyrics: print(line)----------------------------------------------------happy_bday = Song(["Happy birthday to you", "I don't want to get sued ", "Why you dirty rat", "So ill stay right there"])bulls_on_parade = Song(["They rally around tha family", "With pockets full of shells"])print("\n")happy_bday.sing_me_a_song()print("\n")bulls_on_parade.sing_me_a_song()print("\n")```
2 回答
慕桂英546537
TA贡献1848条经验 获得超10个赞
我可以想到两种方法供您执行此操作。
第一种方法是为“for”循环获取循环计数器。第二种方法是使用范围迭代列表或元组。
方法一:
class Song():
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
i = 0
for line in self.lyrics:
i = i + 1 # i here for first line 1 or after print for first line 0
print(str(i) + " : " + line)
方法二:
class Song():
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for i in range(0,len(self.lyrics)):
print(str(i + 1) + " : " + self.lyrics[i]) # i + 1 to start at line 1 or just i to start at line 0
添加回答
举报
0/150
提交
取消