这个“for循环”是如何通过obj的不同行进行索引的

2024-04-19 04:48:23 发布

您现在位置:Python中文网/ 问答频道 /正文

学习Python3艰苦的道路第40课。 我在尽力让我的头脑明白“for loop”是怎么回事。你知道吗

“用于线路输入自我歌词: “打印(行)”

我还想知道如何将“行”转换成一个数字,这样我就可以打印出歌词行上的行号。你知道吗

我稍微修改了一下,换了一行“为什么你这个肮脏的老鼠”,看看它是否能像预期的那样打印出来。我还删除了逗号,并按预期添加了行

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")```

Tags: toselfyouforsongdefline歌词
2条回答

我可以想出两种方法让你做到这一点。你知道吗

第一种方法是为“for”循环获取循环计数器。第二种方法是使用range迭代列表或元组。你知道吗

方法1:

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)

方法2:

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
for i, line in enumerate(self.lyrics):
    ...   

提供iterable的索引和值。你知道吗

相关问题 更多 >