Python尝试覆盖单元格错误 [英] Python Attempt to overwrite cell error
问题描述
我正在尝试创建一个新的excel表,并使用python添加数据。但是,我一直跑进尝试覆盖单元格错误。我不明白的是,根据我写我的代码的方式,我不认为它应该覆盖任何单元格。这是代码:
I am trying to create a new excel sheet and add data to it using python. However, I keep running into the "Attempt to overwrite cell" error. What I don't understand is that according to the way I wrote my code I don't think it should be overwriting any cell. Here is the code:
wb = xlwt.Workbook()
ws = wb.add_sheet('Sheet1', cell_overwrite_ok=True)
for key in DBDICT:
numList = []
for value in DBDICT[key]:
numList.append(float(value))
for i in range(len(DBDICT)):
ws.write(i, 0, key.lat)
ws.write(i, 1, key.lon)
for j in range(len(numList)):
ws.write(i, (j+2), numList[j])
所有我想要做的是从一个名为DBDICT的字典中读取,对于字典中的每一对,写入第一个数字(键是两个数字的元组我使用namedtuple())在excel文件中的某行的第一列中,第二列中的第二个键,然后在每个数字的对应值(这是一个数字列表)中剩余箱子。换句话说,如果
All I am trying to do is read from a dictionary called DBDICT and, for each pair in the dictionary, write the first number of the key (the key is a tuple of two numbers that I made with namedtuple()) in the first column of a certain row in the excel file, the second number of the key in the second column, and then each number of the corresponding value (which is a list of numbers) in the remaining boxes. In other words, if
DBDICT = {(-90, -180):[1.0 , 2.0 , 3.0], (-180, -360):[2.0, 3.0, 4.0]}
然后在第一行excel文件,下面的代码应该写成:
| -90 | -180 | 1.0 | 2.0 | 3.0 |
和第二行
| -180 | -360 | 2.0 | 3.0 | 4.0 |
then in the first row of the excel file, the code below should write: | -90 | -180 | 1.0 | 2.0 | 3.0 | and in the second row: | -180 | -360 | 2.0 | 3.0 | 4.0 |
为什么Python会覆盖单元格?
Why does Python think I'm overwriting a cell?
推荐答案
问题是你在你的字典中循环了两次,这样做会导致很多覆盖!您可以使用枚举
将两个循环组合成一个:
The problem is that you loop twice over your dictionary, which does cause many overwrites! You could combine the two loops into one by using enumerate
:
for i, key in enumerate(DBDICT):
numList = []
for value in DBDICT[key]:
numList.append(float(value))
ws.write(i, 0, key.lat)
ws.write(i, 1, key.lon)
for j in range(len(numList)):
ws.write(i, (j+2), numList[j])
请注意,您也可以在列表中循环两次。这次不会造成任何问题,但可以更有效率。再次使用枚举:
Note that you also loop twice over the list with values. This doesn't cause any problems this time, but it can be more efficient. Again using enumerate:
for i, key in enumerate(DBDICT):
ws.write(i, 0, key.lat)
ws.write(i, 1, key.lon)
for j, val in enumerate(DBDICT[key]):
ws.write(i, j+2, float(val))
这篇关于Python尝试覆盖单元格错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!