【问题标题】:List out of range error in python code列出python代码中的超出范围错误
【发布时间】:2014-11-15 08:22:09
【问题描述】:

我正在编写一个简单的 python 程序,它允许我们列出目录中的所有视频文件并根据用户输入播放它们。但是,在运行此代码时出现列表超出范围错误。

代码:

import os

from subprocess import Popen

def processFile(currentDir):
    # Get the absolute path of the currentDir parameter
    currentDir = os.path.abspath(currentDir)                                         
    global list
    list=[]

    filesInCurDir = os.listdir(currentDir)

    # Traverse through all files
    for file in filesInCurDir:
        curFile = os.path.join(currentDir, file)

        # Check if it's a normal file or directory
        if os.path.isfile(curFile):
            # Get the file extension
            curFileExtension = curFile[-3:]

            # Check if the file has an extension of typical video files
            if curFileExtension in ['avi', 'dat', 'mp4', 'mkv', 'vob']:
                # We have got a video file! Increment the counter
                processFile.counter += 1
                list.append('curFile')

                # Print it's name
                print(processFile.counter,  file)
        else:
            # We got a directory, enter into it for further processing
            processFile(curFile)
if __name__ == '__main__':
    # Get the current working directory
    currentDir = os.getcwd()

    print('Starting processing in %s' % currentDir)

    # Set the number of processed files equal to zero
    processFile.counter = 0

    # Start Processing
    processFile(currentDir)

    # We are done. Exit now.
    print('\n -- %s Movie File(s) found in directory %s --' \
          % (processFile.counter, currentDir))
    print('Enter the file you want to play')
    x = int(input())
    path = list[x-1]
    oxmp=Popen(['omxplayer',path])

【问题讨论】:

  • 哪一行出现超出范围错误?
  • @Crummy:看起来他们得到错误的可能行是倒数第二行 - 它是唯一具有非切片列表索引的行。该问题可能与输入一个不在 1 ... processFile.counter 范围内的数字以响应输入提示有关。
  • list是Python中的保留字,你当然可以用它作为变量名,但是你屏蔽了内置的使用
  • 请阅读stackoverflow.com/help/mcve并提供完整的回溯。
  • 是的,即使输入为 2,我也会在代码的倒数第二行得到错误

标签: python list python-2.7 outofrangeexception


【解决方案1】:

啊哈,发现你的问题了。

在processFile,你说

def processFile(currentDir):
    # ...
    global list
    list=[]
    # ...
    processFile(...)

这意味着,每当您递归时,您都会再次清除列表!这意味着processFile.counter 数字与列表的实际长度不同步。

三点说明:

  • 在像 processFile.counter 这样的函数上存储变量通常是不受欢迎的,AFAIK。
  • 不需要单独的计数器;您只需输入len(list) 即可查找列表中的条目数。
  • 要解决列表问题本身,请考虑在函数外部初始化列表变量或将其作为要修改的参数传入。

【讨论】:

  • 如果答案解决了你的问题,也许接受它?
猜你喜欢
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多