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

Posted

技术标签:

【中文标题】使用类在python中反转字符串数组【英文标题】:Reverse an array of strings in python using a class 【发布时间】:2015-10-07 11:35:22 【问题描述】:

我正在尝试在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()

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

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

【问题讨论】:

【参考方案1】:

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

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

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

【讨论】:

【参考方案2】:

嗯,实际上它们确实有效..

问题是您第一次更改了数据成员。 你输入了 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[:]

【讨论】:

以上是关于使用类在python中反转字符串数组的主要内容,如果未能解决你的问题,请参考以下文章

leetcode刷题反转字符串reverseString(Python)

leetcode刷题反转字符串reverseString(Python)

leetcode刷题反转字符串reverseString(Python)

如何反转字符串数组并使用指针反转每个字符串?

为啥在 Python 2.7 中手动字符串反转比切片反转更糟糕? Slice 中使用的算法是啥?

如何使用交换函数和指针反转字符串数组? (C++)