Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
跨不同文件使用Python函数,并向调用者返回多个值_Python_List_Function_Variables_Return - Fatal编程技术网

跨不同文件使用Python函数,并向调用者返回多个值

跨不同文件使用Python函数,并向调用者返回多个值,python,list,function,variables,return,Python,List,Function,Variables,Return,我想知道如何将列表或字符串返回到变量中。例如,我将以下代码拆分为两个文件: File1.py def example(): number = 3 return number file2.py import file1 name = example() 这个函数给我一个错误,说example()没有定义 还有什么方法可以从一个函数中得到两个变量呢 例如: def example(): number = 3 list = [1 , 2] return li

我想知道如何将列表或字符串返回到变量中。例如,我将以下代码拆分为两个文件:

File1.py

def example():
    number = 3
    return number
file2.py

import file1
name = example()
这个函数给我一个错误,说example()没有定义

还有什么方法可以从一个函数中得到两个变量呢

例如:

def example():
    number = 3
    list = [1 , 2]
    return list
    return number

您需要导入该函数

来自文件1导入示例
name=示例()

导入文件1
name=file1.example()
要从函数返回n个值,您需要返回一些序列,最常见的情况是使用
元组。您可以用逗号分隔return语句中的值

def示例():
数字=3
lst=[1,2]
返回lst,编号
lst,number=example()
值=示例()
lst=值[0]
数字=值[1]
lst,数字=值[0],值[1]

file2.py
中,应使用:

import file1
name = file1.example()
或者您只能导入
example()
函数:

from file1 import example
name = example()
现在,当您键入
name
variable时,您将得到所需的值

还有什么方法可以从一个函数中得到两个变量呢

在我看来,如果你问两个不同的问题会更好;不管怎样,给你:

def example():
    my_number = 3
    my_list = [1, 2]
    return my_list, my_number


list1, number1 = example()
example1 = example()

list1 = example1[0]
number1 = example1[1]
print(number1, list1)


我已经用Python可读格式修改了您的代码,并编辑了您的变量名。

@AustinReedVlog,您只导入了模块文件1。再看看这个答案,它告诉您需要做什么您正在导入模块,并希望它能自动为您解包。再读一遍答案。这回答了你的问题吗?