【问题标题】:Python list out of boundsPython 列表越界
【发布时间】:2015-08-22 10:17:11
【问题描述】:

我在 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

【问题讨论】:

  • 你不需要f.close()。上下文管理器会为您完成这项工作。
  • block = [] 是一个空数组。因此block[0] 超出范围。调试你的代码,看看在什么情况下block 等于[] 当你尝试访问block[0] 时。
  • 每当解析器尝试解析以Hello 开头的块时,块等于[]。这是什么原因造成的?
  • 我试过用你的数据编码。它工作正常。看起来您的真实数据中有一行连续的空行。
  • 我发现了问题。文件末尾是空的。反正有没有忽略那条线?

标签: python list parsing indexoutofboundsexception


【解决方案1】:

只需在您的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 2013-10-19
    • 1970-01-01
    相关资源
    最近更新 更多