list index超出范围:两个列表的迭代

时间:2015-11-13 01:13:13

标签: python list for-loop indexing range

我很难从一个列表中打印文本,并在打印后为每个列表播放声音字节。但是,如果有第二个句子,但没有第二个声音,我将列表索引超出范围。

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

Option Explicit

Sub cartesian_product()

' Set up connection
Dim cn As Object
Set cn = CreateObject("ADODB.Connection")

' Connection string for Excel 2007 onwards .xlsm files
With cn
   .Provider = "Microsoft.ACE.OLEDB.12.0"
   .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
        "Extended Properties=""Excel 12.0 Macro;IMEX=1"";"
    .Open
End With

' Connection string for Excel 97-2003 .xls files
' It should also work with Excel 2007 onwards worksheets
' as long as they have less than 65536 rows
'With cn
'    .Provider = "Microsoft.Jet.OLEDB.4.0"
'    .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
'        "Extended Properties=""Excel 8.0;IMEX=1"";"
'    .Open
'End With

' Create and run the query
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")

' Cartesian product
rs.Open "SELECT [Sheet1$].[Item], [Sheet2$].[Attribute] FROM [Sheet1$], [Sheet2$];", cn

' Output the field names and the results
Dim fld As Object
Dim i As Integer

With Worksheets("Sheet3")
    .UsedRange.ClearContents

    For Each fld In rs.Fields
        i = i + 1
        .Cells(1, i).Value = fld.Name
    Next fld

    .Cells(2, 1).CopyFromRecordset rs
End With

' Tidy up
rs.Close
cn.Close

End Sub

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

好的 -

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

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

答案 2 :(得分:0)

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

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'