简体   繁体   中英

python enumerate function getting index error

I don't understand why the enumeration below. It returns an index error. Since I don't need the index of the enumeration I'm using the under bar. For my understanding y isn't an index. Right? I don't recall where the under bar idea came from but I have used it in the past with good results. Here not so much.

PanelName = ['A1','A2','A3']
PnlCkts = [[1,3,5],[1,4,5],[1,2,4]]

for x in range(len(PanelName)):
    for _,y in enumerate(PnlCkts[x]):
        sql = ("SELECT Ckt, EObjName, Description, Location,"
            + " EObjType, PDF, Spec, "
            + "DwgName FROM EObjDump WHERE Panel = '"
            + PanelName[x]
            + "' AND Ckt = "
            + str(PnlCkts[x][y])
            + ";"
            )

You are making this more complicated than it needs to be.

If you don't need the index, you don't need to use enumerate(PnlCkts[x]) , just iterate over PnlCtks[x] directly.

Then you also don't need to use PnlCkts[x][y] below, y will already be one element from PnlCkts[x] .

for x in range(len(PanelName)):
    for y in PnlCkts[x]:
        sql = ("SELECT Ckt, EObjName, Description, Location,"
            + " EObjType, PDF, Spec, "
            + "DwgName FROM EObjDump WHERE Panel = '"
            + PanelName[x]
            + "' AND Ckt = "
            + str(y)
            + ";"
            )

But, you could actually use enumerate for the iteration over PanelName , since here you do need both the index and the value:

for x, panel in enumerate(PanelName):
    for y in PnlCkts[x]:
        sql = ("SELECT Ckt, EObjName, Description, Location,"
            + " EObjType, PDF, Spec, "
            + "DwgName FROM EObjDump WHERE Panel = '"
            + panel
            + "' AND Ckt = "
            + str(y)
            + ";"
            )

Here's a more advanced technique you might want to be aware of: Since you are processing first PanelName[0] and PnlCkts[0] , then PanelName[1] and PnlCkts[1] , and so on, you can use zip as an idiomatic way to iterate over the two lists in parallel:

for panel, ckts in zip(PanelName, PnlCkts):
    for y in ckts:  # I have no idea what the names mean so I invent one here
        sql = ("SELECT Ckt, EObjName, Description, Location,"
            + " EObjType, PDF, Spec, "
            + "DwgName FROM EObjDump WHERE Panel = '"
            + panel
            + "' AND Ckt = "
            + str(y)
            + ";"
            )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM