【问题标题】:list index out of range: iteration of two lists列表索引超出范围:两个列表的迭代
【发布时间】:2015-11-13 01:13:12
【问题描述】:

我在打印一个列表中的文本以及在打印后为每个列表播放声音字节时遇到了困难。但是,如果有第二个句子,但没有第二个音字节,我会得到列表索引超出范围。

如果第二个列表没有第二个项目怎么办?等等……

import pygame
from pygame.locals import *
pygame.mixer.init()
a="first sentence..."
b="second sentence..."
sentList=[]
sentList.append(a)
sentList.append(b)
sound1= pygame.mixer.Sound('lose1.ogg')
soundList=[]
soundList.append(sound1)
chan1=""
for i in range (len(sentList)):
    print sentList[i]
    chan1= soundList[i].play()
    while chan1.get_busy():
        z=0

【问题讨论】:

标签: python list for-loop indexing range


【解决方案1】:

你可以使用zip,一个简单的例子:

>>> a = [1,2,3]
>>> b = [4,5]
>>> for i,j in zip(a, b):
        print i, j
1 4
2 5

所以你的代码可以是这样的:

for i,j in zip(sentList, soundList):
    print i
    chan1 = j.play()
    while chan1.get_busy():
        z = 0

【讨论】:

    【解决方案2】:

    好的-

    sentList 的长度为 2(您将其附加两次)。 soundList 的长度为 1。在您的 for 循环中,您试图访问不存在的 soundList 的第二个元素。这就是引发错误的原因。要解决此问题,您可以将 chan1= soundList[i].play() 括在 try catch 中,使其看起来像这样。

    try:
        chan1= soundList[i].play()
    except:
        print("error")
    

    【讨论】:

      【解决方案3】:

      您可以输入条件以查看该项目是否存在于列表中:

      if len(soundList) > i:
         chan1= soundList[i].play()
         while chan1.get_busy():
            z=0
      

      或者你使用try 块:

      try:
         chan1= soundList[i].play()
         while chan1.get_busy():
            z=0
      except IndexError:
          print 'ListIndex does not exist'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-16
        • 2018-01-30
        • 1970-01-01
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-16
        相关资源
        最近更新 更多