首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >函数中的变量,或者在else语句之后返回值。

函数中的变量,或者在else语句之后返回值。
EN

Stack Overflow用户
提问于 2017-03-29 10:29:01
回答 2查看 44关注 0票数 0

我是Python的新手,我的函数不像预期的那样工作。我试图将一些值保存在一个列表list_alti中,但是如果我在if或get语句之外调用这些值,则只会得到一个值。

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-29 10:40:27

如果您得到了IndexError,它应该是由i增加的,然后再使用索引list_alt[i]

代码语言:javascript
复制
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

票数 0
EN

Stack Overflow用户

发布于 2017-03-29 11:01:25

通过if/else的行是在i增加之后执行的,因此当然它会打印None,因为这确实是list_alt[i]的值。不管如何,您的函数都应该返回正确的值。如果您希望看到您刚刚插入的值,请考虑两个可能的更改:

  1. 增量i作为while循环中的最后一行
  2. print(list_alt[i-1])代替
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43090989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档