I'm having difficulty with printing text from one list, and playing the soundbyte for each list after it prints. However if there is a second sentence, but no second soundbyte, I get list index out of range.
我很难从一个列表中打印文本,并在打印后为每个列表播放声音字节。但是,如果有第二个句子,但没有第二个声音,我得到列表索引超出范围。
What do I do if the second list has no second item? etc...
如果第二个列表没有第二个项目,我该怎么办?等等...
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
3 个解决方案
#1
1
you can use zip
, a simple example:
你可以使用zip,一个简单的例子:
>>> a = [1,2,3]
>>> b = [4,5]
>>> for i,j in zip(a, b):
print i, j
1 4
2 5
so your code can be like this:
所以你的代码可以是这样的:
for i,j in zip(sentList, soundList):
print i
chan1 = j.play()
while chan1.get_busy():
z = 0
#2
0
Ok -
好 -
sentList
has a length of 2 (you append it twice). soundList
has a length 1. In your for loop, you are trying to access the second element of soundList
, which does't exist. That is why an error is thrown. To solve this, you can enclose chan1= soundList[i].play()
in a try catch to look like this.
sentList的长度为2(您将其追加两次)。 soundList的长度为1.在for循环中,您尝试访问soundList的第二个元素,该元素不存在。这就是抛出错误的原因。要解决这个问题,你可以在try catch中包含chan1 = soundList [i] .play(),看起来像这样。
try:
chan1= soundList[i].play()
except:
print("error")
#3
0
you can put a condition in to see if the item exists in the list:
你可以放入一个条件来查看列表中是否存在该项:
if len(soundList) > i:
chan1= soundList[i].play()
while chan1.get_busy():
z=0
or you use a try
block:
或者您使用try块:
try:
chan1= soundList[i].play()
while chan1.get_busy():
z=0
except IndexError:
print 'ListIndex does not exist'
#1
1
you can use zip
, a simple example:
你可以使用zip,一个简单的例子:
>>> a = [1,2,3]
>>> b = [4,5]
>>> for i,j in zip(a, b):
print i, j
1 4
2 5
so your code can be like this:
所以你的代码可以是这样的:
for i,j in zip(sentList, soundList):
print i
chan1 = j.play()
while chan1.get_busy():
z = 0
#2
0
Ok -
好 -
sentList
has a length of 2 (you append it twice). soundList
has a length 1. In your for loop, you are trying to access the second element of soundList
, which does't exist. That is why an error is thrown. To solve this, you can enclose chan1= soundList[i].play()
in a try catch to look like this.
sentList的长度为2(您将其追加两次)。 soundList的长度为1.在for循环中,您尝试访问soundList的第二个元素,该元素不存在。这就是抛出错误的原因。要解决这个问题,你可以在try catch中包含chan1 = soundList [i] .play(),看起来像这样。
try:
chan1= soundList[i].play()
except:
print("error")
#3
0
you can put a condition in to see if the item exists in the list:
你可以放入一个条件来查看列表中是否存在该项:
if len(soundList) > i:
chan1= soundList[i].play()
while chan1.get_busy():
z=0
or you use a try
block:
或者您使用try块:
try:
chan1= soundList[i].play()
while chan1.get_busy():
z=0
except IndexError:
print 'ListIndex does not exist'