【问题标题】:'Merge' two objects in python在python中“合并”两个对象
【发布时间】:2014-11-29 14:03:06
【问题描述】:

我试图弄清楚如何将两个对象“合并”在一起。我的目标是合并两个 Album 对象(代码如下)。我需要能够合并多个Album 对象的tracks 参数(它们是列表),前提是Album 对象的'title' 参数相同。

基本上,如果我有一个Album 对象,其中tracks 参数的长度为1,另一个专辑对象tracks 参数的长度也为1,则新的或更新的单数Album对象需要有一个长度为 2 的 tracks 参数。

我已经发布了我的代码来展示对象是如何定义的。

提前致谢!

编辑:由于tracks 参数列表中的每个元素都是歌曲名称,我想保留相同的元素并将它们放在新的或更新的tracks 参数中。我需要将每个对象的确切元素放入这个“新”对象中,而不是仅仅改变元素的数量。

class Album(object) :
    def __init__(self, artist, title, tracks = None) :
        tracks = []
        self.artist = artist
        self.title = title
        self.tracks = tracks

    def add_track(self, track) :
        self.track = track
        (self.tracks).append(track)
        print "The track %s was added." % (track)

    def __str__(self) :
        if len(self.tracks) == 1 :
            return "Artist: %s, Album: %s [" % (self.artist, self.title) + "1 Track]"
        return "Artist: %s, Album: %s [" % (self.artist, self.title) + str(len(self.tracks)) + " Tracks]"

【问题讨论】:

  • have the exact elements from each object put into this 'new' object. 是什么意思?
  • @Kasra 如果专辑对象 1 的 tracks 列表是 ['one'] 并且专辑对象 2 的“曲目”列表是 ['two'],那么最终的 tracks 列表将是 ['one', 'two']。我输入这些信息是因为我不想只添加两个列表的长度,我希望将元素添加到一个新列表中。

标签: python class object merge arguments


【解决方案1】:

合并算法必须知道类的内部数据结构。因此,将合并代码放在类中似乎是合乎逻辑的。下面的代码可以做到这一点,并允许合并两个专辑,只需添加它们 (album1 + album2):

class Album(object) :
    def __init__(self, artist, title, tracks = None) :
        self.artist = artist
        self.title = title
        self.tracks = tracks

    def add_track(self, track) :
        self.track = track
        (self.tracks).append(track)
        print "The track %s was added." % (track)

    def __str__(self) :
        if len(self.tracks) == 1 :
            return "Artist: %s, Album: %s [" % (self.artist, self.title) + "1 Track]"
        return "Artist: %s, Album: %s [" % (self.artist, self.title) + str(len(self.tracks)) + " Tracks]"

    def __add__(self, other):
        if self.artist != other.artist or self.title != other.title:
            raise ValueError("Albums are incommensurable")
        return Album(self.artist, self.title, self.tracks + other.tracks)

这个用法如下:

>>> a = Album('Joe', "Joe's First", tracks=['Beer', 'Trucks'])
>>> b = Album('Joe', "Joe's First", tracks=['Bourbon', 'Tequila'])
>>> complete = a + b
>>> print complete
Artist: Joe, Album: Joe's First [4 Tracks]
>>> complete.tracks
['Beer', 'Trucks', 'Bourbon', 'Tequila']

【讨论】:

    【解决方案2】:

    关于保留您不需要的相同元素,您只需要在添加曲目之前检查if 条件:

    def add_track(self, track) :
        self.track = track
        if track not in (self.tracks) :
             (self.tracks).append(track)
        else :
             raise ValueError("duplicate track")
        print "The track %s was added." % (track)
    

    【讨论】:

      【解决方案3】:
      def merge_albums(album1, album2):
          if not album1.artist == album2.artist and \
                  album1.title == album2.title:
              raise SomeException("Albums don't match")
          new_tracks = list(set(album1.tracks + album2.tracks))
          return Album(album1.artist, album1.title, new_tracks)
      

      【讨论】:

        【解决方案4】:

        我假设您只有在艺术家和标题相同的情况下才会合并专辑的曲目。一种方法是定义您自己的合并函数,如下所示:

        class Album(object) :
            def __init__(self, artist, title, tracks = None) :
                tracks = []
                self.artist = artist
                self.title = title
                self.tracks = tracks
        
            def add_track(self, track) :
                self.track = track
                (self.tracks).append(track)
                print "The track %s was added." % (track)
        
            def merge(self, album):
                if (type(self)==type(album)):
                    if self.artist == album.artist and self.title==album.title:
                        self.tracks.extend(album.tracks)
                    else:
                        print "cannot merge albums, artists or titles are not same"
                else:
                    print "Invalid object types, cannot merge"
            def __str__(self) :
                if len(self.tracks) == 1 :
                    return "Artist: %s, Album: %s [" % (self.artist, self.title) + "1 Track]"
                return "Artist: %s, Album: %s [" % (self.artist, self.title) + \
                       str(len(self.tracks)) + " Tracks]"
        

        那么如果你有专辑 a,你可以调用 a.merge(b) 合并后 a.tracks 应该包含合并的曲目。您需要根据需要进行其他更改。

        【讨论】:

          猜你喜欢
          • 2013-01-28
          • 1970-01-01
          • 2017-06-11
          • 1970-01-01
          • 2021-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-25
          相关资源
          最近更新 更多