使用类反转python中的字符串数组

2024-10-01 19:31:33 发布

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

我试着在Python中学习class,下面是我为自己做的一个练习。我想创建一个类,可以定期唱一首歌,也可以反过来唱一首歌。下面是我键入的内容:

class Song(object):

   def __init__(self, lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print line
    def sing_me_a_reverse_song_1(self):
        self.lyrics.reverse()
            for line in self.lyrics:
                print line
    def sing_me_a_reverse_song_2(self):
        for line in reversed(self.lyrics):
            print line
    def sing_me_a_reverse_song_3(self):
        for line in self.lyrics[::-1]:
            print line

bulls_in_parade = Song(["They rally around the family",
                    "with pockets full of shells"])
#sing it for me                     
bulls_in_parade.sing_me_a_song()

#1st method of reversing:
bulls_in_parade.sing_me_a_reverse_song_1()

#2nd method of reversing:   
bulls_in_parade.sing_me_a_reverse_song_2()

#3rd method of reversing:   
bulls_in_parade.sing_me_a_reverse_song_3()             

第一种反转方法非常有效,但我不知道为什么我不能让最后两种方法工作。你知道吗

以下是我在输出中得到的结果:

They rally around the family
with pockets full of shells
----------
with pockets full of shells
They rally around the family
----------
They rally around the family
with pockets full of shells
----------
They rally around the family
with pockets full of shells

下面是我想在输出中看到的:

They rally around the family
with pockets full of shells
----------
with pockets full of shells
They rally around the family
----------
with pockets full of shells
They rally around the family
----------
with pockets full of shells
They rally around the family

如果在一个单独的函数中定义最后两个方法,它们将正常工作,但我不明白为什么它们在我的类中不工作。你知道吗

我认为问题应该出在“调用”lyrics

self.lyrics()

如果是的话,帮我解决这个问题。你知道吗

我还要补充一点,我使用的是Python2.7


Tags: oftheinselfwithfamilyfullaround
2条回答

它们都工作得很好,只是你的第一个方法改变了列表,所以其他方法正在反转已经反转的列表,所以它们实际上回到了原来的顺序!你知道吗

def sing_me_a_reverse_song_1(self):
    self.lyrics.reverse()  # <  - lyrics is now reversed
    for line in self.lyrics:
        print line

调用此方法后,任何其他尝试访问self.lyrics的时间都将被反转(除非将其反转回原始顺序)

好吧,事实上他们确实有用。。你知道吗

问题是您第一次更改了数据成员。 你打字了self.歌词.revese(),从那时起,列表一直颠倒。你知道吗

您可以这样修复方法:

def sing_me_a_reverse_song_1(self):
    tmpLyrics = self.lyrics[:]
    tmpLyrics.reverse()
    for line in tmpLyrics:
        print line

注意:

不要做tmpLyrics = self.lyrics,因为python通过引用传递list,因此正确的方法是tmpLyrics = self.lyrics[:]

相关问题 更多 >

    热门问题