Python - 从元组返回一个值

时间:2014-03-20 16:48:22

标签: python oop methods instance generator

我使用pyacoustid并且我不明白为什么这段代码有效(艺术家实际上是艺术家等等):

first = True
        for score, rid, title, artist in self.fpresults:
            if first:
                first = False
            else:
                print
            print '%s - %s' % (artist, title)
            print 'http://musicbrainz.org/recording/%s' % rid
            print 'Score: %i%%' % (int(score * 100))

虽然这个块没有(当我打印它时似乎是空的):

def getFingerprintArtist(self):
        """
        Returns tuples with possible artists fetched from the MusicBrainz DB
        """
        return  [artist for score, rid, title, artist in self.fpresults]

以下是全班(欢迎提出建议!):

class SongFP:
    """
    Song with FINGERPRINTS
    """
    fpresults = None

    def __init__(self, path = None):
        """
        :param path: the path of the song
        """
        self.path = path
        try:
            self.fpresults = acoustid.match(api_key, path)
        except acoustid.NoBackendError:
            logger(paths['log'], "ERROR: chromaprint library/tool not found")
        except acoustid.FingerprintGenerationError:
            logger(paths['log'], "ERROR: fingerprint could not be calculated")
        except acoustid.WebServiceError, exc:
            logger(paths['log'], ("ERROR: web service request failed: %s" % exc.message))

    def setPath(self, path):
        self.path = path

    def printResults(self):
        first = True
        for score, rid, title, artist in self.fpresults:
            if first:
                first = False
            else:
                print
            print '%s - %s' % (artist, title)
            print 'http://musicbrainz.org/recording/%s' % rid
            print 'Score: %i%%' % (int(score * 100))

    def setFPResults(self):
        self.fpresults = acoustid.match(api_key, self.path)

    def getFingerprintArtist(self):
        """
        Returns tuples with possible artists fetched from the MusicBrainz DB
        """
        return [artist for score, rid, title, artist in self.fpresults]

    def getFingerprintTitle(self):
        """
        Returns tuples with possible titles fetched from the MusicBrainz DB
        """
        return [title for score, rid, title, artist in self.fpresults]

    def getFingerPrintID(self):
        """
        Returns tuples with IDs fetched from the MusicBrainz DB
        """
        return [rid for score, rid, title, artist in self.fpresults]

    def getFingerPrintScore(self):
        """
        Returns tuples with scores fetched from the MusicBrainz DB
        """
        return [score for score, rid, title, artist in self.fpresults]

注意: acoustid.match(api_key, path)会返回元组!

编辑:

这个小例子

songfp = SongFP(sys.argv[1])
songfp.printResults()

其中SongFP

class SongFP:
    """
    Song with FINGERPRINTS
    """
    fpresults = None

def __init__(self, path = None):
    """
    :param path: the path of the song
    """
    self.path = path
    try:
        self.fpresults = acoustid.match(api_key, path)
    except acoustid.NoBackendError:
        logger(paths['log'], "ERROR: chromaprint library/tool not found")
    except acoustid.FingerprintGenerationError:
        logger(paths['log'], "ERROR: fingerprint could not be calculated")
    except acoustid.WebServiceError, exc:
        logger(paths['log'], ("ERROR: web service request failed: %s" % exc.message))

def getFingerprintArtist(self):
        """
        Returns tuples with possible artists fetched from the MusicBrainz DB
        """
        return [artist for _, _, _, artist in self.fpresults]

def getFingerprintTitle(self):
    """
    Returns tuples with possible titles fetched from the MusicBrainz DB
    """
    return [title for _, _, title, _ in self.fpresults]

def getFingerprintID(self):
    """
    Returns tuples with IDs fetched from the MusicBrainz DB
    """
    return [rid for _, rid, _, _ in self.fpresults]

def getFingerprintScore(self):
    """
    Returns tuples with scores fetched from the MusicBrainz DB
    """
    return [score for score, _, _, _ in self.fpresults]

def printResults(self):
        print("Titles: %s" % self.getFingerprintTitle())
        print("Artists: %s" % self.getFingerprintArtist())
        print("IDs: %s" % self.getFingerprintID())
        print("Scores: %s" % self.getFingerprintScore())

当被称为./app song.mp3时只输出一些字段(如果一个字段为空,那么所有其他字段也应该反之,反之亦然,因为它获取在线MP3元数据)

Titles: [u'Our Day Will Come', u'Our Day Will Come', u'Our Day Will Come', u'Our Day Will Come', u'Our Day Will Come']
Artists: []
IDs: []
Scores: []

日志中没有例外情况!

3 个答案:

答案 0 :(得分:2)

很难对此进行诊断,但通常更常见的是分配您不使用的变量:

def getFingerprintArtist(self):
    """
    Returns (list of)* possible artists fetched from the MusicBrainz DB
    """
    return  [artist for _, _, _, artist in self.fpresults]

您能否将此重写为可重复性最小的示例,以便我们提供进一步的指导?

*这并不会返回一个元组,它只是返回一个(语义上讲)艺术家名字的列表!


编辑 - 分析

我认为这里发生的事情是你正在耗尽发电机。

self.fpresults

在对象的实例化中填充一次,而在__init__执行此操作:

try:
    self.fpresults = list(acoustid.match(api_key, path))

它会将生成器在内存中生成的信息保存为属性,直到listSongFP对象被解除引用,然后进行垃圾回收。

答案 1 :(得分:0)

如果他们只是元组,你可以这样做:

def get_value_at_index(tuple_list, index):
    """Returns a list of the values at a given index."""
    return [tup[index] for tup in tuple_list]

答案 2 :(得分:0)

[artist for score, rid, title, artist in self.fpresults]

你只是商店艺术家。你需要这样的东西:

[(artist, score, rid, title) for artist, score, rid, title in self.fpresults]