繁体   English   中英

如何从函数外部的函数中使用变量

[英]how to use a variable from a function outside the function

我需要使用在函数外部的函数内部创建的变量

ls1 = []
ls2 = []
def process_line(filename):
            i = 0
            global ls 1
            global ls2
            tup = ()
            while i<len(filename):
                if i%2==0:
                    ls1.append(float(filename[i]))
                else:
                    ls2.append(float(filename[i]))
                i += 1
            tup = tup + (ls1, )
            tup = tup + (ls2, )
            return tup
        process_line(filename)
if command == 'regular':
        k = 0
        print('Regular Transactions:')
        while k<7:
            print('{}: +{:.2f} -{:.2f}'.format(weekdays[k], ls1[k], ls2[k]))

但是,据写ls1和ls2没有定义。 如何调用变量?

您也可以返回这些变量。 您还有其他一些问题:

def process_line(filename):
            i = 0
            ls1 = []
            ls2 = []
            tup= ()
            while i<len(filename):
                if i%2==0:
                    ls1.append(float(filename[i]))
                else:
                    ls2.append(float(filename[i]))
                i += 1
            tup = tup + (ls1, )
            tup = tup + (ls2, )
            return tup, ls1, ls2
tup, ls1, ls2 = process_line(filename)
if command == 'regular':
        k = 0
        print('Regular Transactions:')
        while k<7:
            print('{}: +{:.2f} -{:.2f}'.format(weekdays[k], ls1[k], ls2[k])
        k += 1
  1. 您需要先调用该函数才能运行
  2. 您需要在while循环中增加k,否则它将永远运行。
  3. 我也不确定应该是什么图珀? 如果要使用ls1和ls1的元组,则可能只需在返回行之前调用tup = (ls1, ls2)并在process_line的结尾处进行操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM