![](/img/trans.png)
[英]How can I print whether the number in the specified index is positive or negative in python using exception handling?
[英]How to find specified data in excel by using python (positive number first appeared and negative number nearby)
我想在excel的每一行中搜索數據,並找出順序出現在A之前的第一個出現的正數(A)和一個負數(B) 。 像:-5 -6 -3 4 1我需要數字-3和4
我嘗試使用這種代碼:
import xlrd
testFile=xlrd.open_workbook('test.xls')
mySheet=testFile.sheet_by_name("Sheet1")
nrows=mySheet.nrows
ncols=mySheet.ncols
def f(j):
value=mySheet.cell(0,j).value
return value
for j in range(ncols):
if f(j)*f(j*1)>0:
print f(j),f(j+1)
但是當我運行它時,會出現錯誤:
追溯(最近一次通話):
(模塊)中第15行的文件“ test1.py”
打印f(j),f(j + 1)
在f的文件“ test1.py”的第10行
值= mySheet.cell(0,j)的。價值
單元格中的文件“ C:\\ Python27 \\ lib \\ site-packages \\ xlrd \\ sheet.py”,行399
self._cell_types [rowx] [colx],
IndexError:數組索引超出范圍
我不知道為什么不能使用函數f(j)*f(j+1)>0
來找出第一個正數和附近的負數。 有人會幫助發現問題嗎?
您的范圍是從0到j。 您正在嘗試訪問j + 1值。 因此,IndexError:數組索引超出范圍。
另外,如果f(j)* f(j * 1)> 0,您正在做:f(j)* f(j + 1)<0,您可能想做:在這里我更改了2件事。 將j * 1設為j + 1,並將> 0設為<0。 您正在檢查負數是否為負數。 f(j)* f(j * 1)應保持> 0,直到u找到第一個正數。
為了解決索引超出范圍的問題,請循環運行直到(ncols-1)
您也可以以更高效的方式進行操作。 只需檢查數字是否為正。 如果是,則返回該值和前一個索引的值。 您不必乘以,這是一個額外的耗時命令
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.