Python脚本问题

2024-05-14 00:12:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有一个问题,我的输出是:

Traceback (most recent call last):
File "1stHour.py", line 48, in
ws1.cell(column=1, row=i, value="%s" % blue_student_list[i])
IndexError: list index out of range`

# coding=utf:8
from pythonzenity import Message
from openpyxl.styles import PatternFill
from openpyxl import Workbook
import bluetooth
import time



def student_check(index):
    result = bluetooth.lookup_name(blue_address_list[index], timeout=3)
    if (result is not None):
        return True
    else:
        return False

blue_student_list = ['Name', 'Name2']
blue_address_list = ['Address', 'Address2']


redFill = PatternFill(start_color='FF0000', end_color='FF0000', fill_type='solid')
greenFill = PatternFill(start_color='00FF00', end_color='00FF00', fill_type='solid')


for i in range(0, len(blue_address_list)):

    i = i + 1

    ws1.cell(column=1, row=i, value="%s" % blue_student_list[i])
    if (student_check(i)):
       ws1.cell(column=2, row=i, value="%s" % "Present").fill = greenFill
    else:
       ws1.cell(column=2, row=i, value="%s" % "Absent").fill = redFill


Message(title="Attendance Checker",text="You can now open the Excel Document on your Desktop", timeout=3000)

我有这个工作,但忘记保存它,所以我不再有正确的方式,我有它以前在这里。我能做些什么来防止这个错误?我觉得我好像忘了什么,或者在代码的i = i + 1部分写东西。在


Tags: fromimportindexvalueaddresscellcolumnblue
2条回答

在openpyxl中,行和列是1索引的,因此ws['A1']对应于{}。在

IndexError几乎可以肯定来自blue_student_list[i]查找。最好使用一个额外的行来获取值,避免使用“%s”格式,因为在这里完全没有必要。在

for idx, value in enumerate(blue_student_list, start=1):
    ws1.cell(column=1, row=idx, value=value)

执行此操作时:

for i in range(0, len(blue_address_list)):

无需同时执行以下操作:

^{pr2}$

这样做会导致你看到的错误类型。在

您似乎在这样做,因为您使用的库使用基于1的索引,而不是Python列表中基于0的索引。但在执行此操作时,您仍然使用(1太高)i来索引到列表中:

blue_student_list[i]

因此,与其第二次递增i,不如将一个高出1的值传递给需要它的对象:

ws1.cell(column=1, row=i+1, value="%s" % blue_student_list[i])

在对ws1.cell的其他调用中也是如此。在

这是。。至少可以说,对于Python库来说是不寻常的,因此在您第一次使用row=i+1之前,它可能需要添加这样的注释:

# Need row=i+1 because openPyXML uses 1-based indexing

相关问题 更多 >