for循环内的字典导致TypeError,for循环外的字典工作

2024-07-02 11:41:37 发布

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

基本上我要做的是搜索excel文件中一列中的所有值,如果它们与另一个文本文件中的任何数据值匹配,则将它们标记为绿色。你知道吗

我很抱歉,如果我的代码很难阅读,仍然非常初学者。你知道吗

因此,下面的将运行良好,并打印字典“dictIPExcel”没有问题:

dictIPExcel = {}
##############IMPORTANT CHANGE HERE, FILE NAME########################
#Change file name here to suit your file
wb = openpyxl.load_workbook('file.xlsx')
#Copy sheet name here
sheet = wb.active

#What font color to change to below

greenFill = PatternFill(start_color='0000B200', end_color='0000B200', fill_type='solid')

#This will create a list containing every line in the below txt file
IPlist = open('No Config or Denied devices.txt').read().split('\n')

#Loops through A19-A100, gathering the value in each row into dictIPExcel
for t in range(19,100):
    dictIPExcel["A{0}".format(t)] = sheet['A'+ str(t)].value
print dictIPExcel
sheetz = wb.sheetnames

for a in sheetz:
    sheet = a
    dictIPExcel = {}

    for l in range(19,100):
        for x,y in dictIPExcel.items():
            for z in IPlist:
                if y == z:
                    print "match"
                    sheet[x].fill = greenFill
wb.save('textCopy4.xlsx')

但是,如果我将“dictIPExcel”移到第二个for循环中,它会抛出一个“TypeError:Strings must be integers”。现在据我所知,这意味着将“A50”作为字典中的索引基本上是不合适的。我的问题是为什么这在循环之外工作?字典中的数据索引在循环外和循环内没有变化,但是错误只在循环内抛出。内部有循环的代码:

for a in sheetz:
    sheet = a
    dictIPExcel = {}
    for t in range(19,100):
        dictIPExcel["A{0}".format(t)] = sheet['A'+ str(t)].value
    for l in range(19,100):
        for x,y in dictIPExcel.items():
            for z in IPlist:
                if y == z:
                    print "match"
                    sheet[x].fill = greenFill

以下是输出:

Traceback (most recent call last):
  File "C:..\testing.py", line 49, in <module>
    dictIPExcel["A{0}".format(t)] = sheet['A'+ str(t)].value
TypeError: string indices must be integers

我能做些什么让它在循环中运行吗?或者也许有更好的方法来处理我正在尝试做的事情,即浏览每一页并突出显示匹配的数据?你知道吗


Tags: to数据infor字典valuerangefill
3条回答

sheetz是图纸名称的列表,它们是字符串。您需要使用wb.get_sheet_by_name获取句柄

for a in sheetz:
    sheet=wb.get_sheet_by_name(a)
    dictIPExcel = {}
    for t in range(19,100):
        dictIPExcel["A{0}".format(t)] = sheet['A' + str(t)].value

我不相信这与我们有任何关系。错误表明变量sheetstr,而不是您处理它时的dict。你知道吗

请看:

#Copy sheet name here
sheet = wb.active

然后在这里覆盖它:

for a in sheetz:
    sheet = a

我假设是基于sheetz = wb.sheetnamesstr。你知道吗

这是对python的一个常见误解。For循环没有自己的变量名称空间,而内部变量可以在其作用域之外关闭变量。例如:

>>> for i in range(5): pass
... 
>>> print i
4
>>> 

如果在循环中使用不同的变量(sheet_name?),你应该很好。你知道吗

祝你好运!你知道吗

在第一种情况下(正确的)

sheet = wb.active

所以sheet是一个字典。

在第二种(不正确的)情况下

sheet = a   # for a in sheetz, where  sheetz = wb.sheetnames

sheet是一个列表(因此它需要整数索引)。你知道吗

相关问题 更多 >