Python列表超出范围

时间:2015-06-08 03:24:13

标签: python list parsing indexoutofboundsexception

我在python中有以下函数,它接受输入并将其解析为字典。我试图传递它以下输入,由于某些原因,行artist=block[0]导致它中断,因为列表索引超出范围,我真的很困惑为什么。在第二个Led Zeppelin中阅读后它会中断。对此问题的任何帮助将不胜感激。

输入

Led Zeppelin
1969 II
-Whole Lotta Love
-What Is and What Should Never Be
-The Lemon Song
-Thank You
-Heartbreaker
-Living Loving Maid (She's Just a Woman)
-Ramble On
-Moby Dick
-Bring It on Home

Led Zeppelin
1979 In Through the Outdoor
-In the Evening
-South Bound Saurez
-Fool in the Rain
-Hot Dog
-Carouselambra
-All My Love
-I'm Gonna Crawl

Hello
Hello
Hello
Hello

Bob Dylan
1966 Blonde on Blonde
-Rainy Day Women #12 & 35
-Pledging My Time
-Visions of Johanna
-One of Us Must Know (Sooner or Later)
-I Want You
-Stuck Inside of Mobile with the Memphis Blues Again
-Leopard-Skin Pill-Box Hat
-Just Like a Woman
-Most Likely You Go Your Way (And I'll Go Mine)
-Temporary Like Achilles
-Absolutely Sweet Marie
-4th Time Around
-Obviously 5 Believers
-Sad Eyed Lady of the Lowlands

功能

def add(data, block):
    artist = block[0]
    album = block[1]
    songs = block[2:]
    if artist in data:
        data[artist][album] = songs
    else:
        data[artist] = {album: songs}
    return data

def parseData():

    global data,file
    file=os.getenv('CDDB')
    data = {}
    with open(file) as f:
        block = []
        for line in f:
            line = line.strip()
            if line == '':
                data = add(data, block)
                block = []
            else:
                block.append(line)
        data = add(data, block)
        f.close()


    return data

1 个答案:

答案 0 :(得分:2)

只需在您的add()功能中添加健全性检查:

def add(data, block):
    if not block:
        return

此外,没有充分的理由使用全局变量。这是一个例子:

def parseData(path):

    data = {}
    block = []

    with open(path) as f:
        for line in f:
            line = line.strip()
            if line == '':
                add(data, block)
                block = []
            else:
                block.append(line)
        add(data, block)

    return data