2014-10-04 1 views
2

두 개체를 병합하는 방법을 알아 내려고하고 있습니다. 여기 내 목표는 두 개의 Album 개체 (아래 코드)를 병합하는 것입니다. Album 개체의 'title'인수가 같은 경우에만 Album 개체의 tracks 인수 (목록)를 병합 할 수 있어야합니다. 나는 tracks 인수의 길이가 1 인 Album 객체와 tracks 인수의 길이도 한 또 다른 앨범 개체, 새로운, 또는 업데이트 된 단일 Album 객체가있는 경우'병합'파이썬에서 두 개체

기본적으로 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]" 
+0

'각 개체의 정확한 요소를이'새 '개체에 넣었습니까? '? – Kasramvd

+0

@Kasra 앨범 객체 1의'tracks'리스트가'[ 'one']'이고 앨범 객체 2의 'tracks'리스트가'[ 'two']'이면 최종'tracks'리스트는'[ 'one' , 'two']'. 나는 두리스트의 길이가 더해지기를 원하지 않기 때문에이 정보를 넣었습니다. 나는 요소들을 새로운리스트에 추가하기를 원합니다. –

+0

답변을 추가하십시오! – Kasramvd

답변

2

병합 알고리즘은 클래스의 내부 데이터 구조를 알아야합니다. 따라서 병합 코드를 클래스 내에 넣는 것이 논리적 인 것처럼 보입니다. 아래 코드는이 작업을 수행하고이 앨범은 (album1 + album2)에 추가 단순히 병합 할 수 있습니다 :

>>> 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'] 
0

당신이 것을하지 않아도 같은 요소를 유지에 관하여 다음과 같이

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) 

이 사용

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

I : 당신은 이전에 트랙을 추가 확인하려면 if 조건이 필요합니다 아티스트와 제목이 동일한 경우에만 앨범의 트랙을 병합한다고 가정합니다. 이렇게하는 한 가지 방법은 다음과 같이 자신의 병합 함수를 정의하는 것입니다 :

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를 호출 할 수 있습니다. 원하는대로 다른 변경 작업을 수행해야합니다.