我是Python的新手,我的功能没有按预期工作。我试图在列表list_alt [i]中保存一些值,但如果我调用if或else语句之外的值,我只得到None。
import os.path
import xlrd
import sys
import argparse
def readExcel():
workbook = xlrd.open_workbook(path)
sheet = workbook.sheet_by_index(0)
sheet = workbook.sheet_by_index(0)
j=0
for row in range(sheet.nrows):
j += 1
rownumber=j
print (rownumber)
k=0
i=0
list_alt=[None]*j
list_neu=[None]*j
while (i<j-10):
#get first row values
temp = sheet.cell_value(k,0).replace('www.website.com/','')
#get second row values
temp2 = sheet.cell_value(k,1)
if "http:" in temp2:
temp2 = sheet.cell_value(k,1).replace('http:','https:')
list_neu[i]=temp2
list_alt[i]=temp
k+=0
i+=1
else:
list_neu[i]=temp2
list_alt[i]=temp
#i can print the values here
print (list_alt[i])
print (list_neu[i])
i+=1
k+=1
#I cant print for the values here anymore
print (list_alt[i])
print (list_neu[i])
print (i)
return list_alt, list_neu
答案 0 :(得分:1)
if/else
增加后,> i
以后的行会被执行,因此它会打印None
,因为这确实是{的值{ {1}}。无论如何,您的函数应返回正确的值。如果您希望看到刚插入的值,请考虑两种可能的更改:
list_alt[i]
增加为while循环中的最后一行i
而不是答案 1 :(得分:0)
如果您获得IndexError
,则应该在使用之前通过索引i
来增加list_alt[i]
。
import os.path
import xlrd
import sys
import argparse
def readExcel():
workbook = xlrd.open_workbook(path)
sheet = workbook.sheet_by_index(0)
sheet = workbook.sheet_by_index(0)
j=0
for row in range(sheet.nrows):
j += 1
rownumber=j
print (rownumber)
k=0
i=0
list_alt=[None]*j
list_neu=[None]*j
while (i<j-10):
temp = sheet.cell_value(k,0).replace('www.website.com/','')
temp2 = sheet.cell_value(k,1)
if "http:" in temp2:
temp2 = sheet.cell_value(k,1).replace('http:','https:')
list_neu[i]=temp2
list_alt[i]=temp
k+=0
# variable i is increased.
i+=1
elif "http" not in temp2:
print ("not there")
k+=1
else:
list_neu[i]=temp2
list_alt[i]=temp
print (list_alt[i])
print (list_neu[i])
# variable i is increased.
i+=1
k+=1
# variable i is increased before.
# you may purpose to read list_alt[i-1].
print (list_alt[i])
print (i)
return list_alt, list_neu
我希望我的回答很有帮助。 :d