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

Python 如何使用函数外部函数中的变量,python,Python,我需要使用在函数外部的函数内部创建的变量 ls1 = [] ls2 = [] def process_line(filename): i = 0 global ls 1 global ls2 tup = () while i<len(filename): if i%2==0: ls1.append(f

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

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
您需要在函数运行之前调用它 您需要在while循环中增加k,否则它将永远运行。 我也不知道tup应该是什么?如果您想要一个包含ls1和ls1的元组,您可能只需要调用tup=ls1、ls2和返回行之前的进程结束行。
这可能会有帮助:要在函数外部使用值,您应该从函数返回值。您甚至从未调用过函数,而且您真正想要的似乎不是使用我在函数外部的函数内部创建的变量。你想要的是使用从函数返回的值,也就是ls1和ls2I'm not OP的元组-为什么是下一票?有人修改了这个问题,所以他们的答案现在是发布的代码@ygnaiyu,你能把代码还原成你原来的代码吗?这能回答你的问题吗?