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

时间:2015-07-17 17:01:04

标签: python arrays class python-2.7 arraylist

我试图在class中学习Python,这是我为自己做的一个练习。我想创建一个可以定期唱一首歌并且反过来唱一首歌的课程。所以这就是我输入的内容:

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()

如果有,请帮我解决这个问题。

而且我还要补充一点,我使用的是python 2.7

2 个答案:

答案 0 :(得分:3)

它们都运行良好,只是你的第一个方法改变了列表,所以其他方法正在颠倒已经反转的列表,所以它们实际上又恢复了原来的顺序! / p>

Rx.Observable.timer(0, 2000)
  .flatMap($response)
  .subscribe(response => {
    console.log('Got the response');
  });

在您调用此方法后,在您尝试访问def sing_me_a_reverse_song_1(self): self.lyrics.reverse() # <----- lyrics is now reversed for line in self.lyrics: print line 的任何其他时间它仍然会被撤消(除非您将其反转回原来的顺序)

答案 1 :(得分:0)

好吧,实际上他们确实有效..

问题是您是第一次更改了数据成员。 你键入了self.lyrics.revese(),从那时起,列表就会反转。

你可以修改这样的方法:

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

注意:

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