return中如何返回多个值
时间: 2024-04-30 15:24:18 浏览: 18
在 Python 中,可以使用元组(tuple)来返回多个值。例如:
```
def my_function():
# 假设这里有一些计算,得到了两个结果
result1 = 10
result2 = 'hello'
# 使用元组返回结果
return result1, result2
# 调用函数,并获取多个返回值
r1, r2 = my_function()
print(r1) # 输出 10
print(r2) # 输出 'hello'
```
另外,还可以使用字典(dict)或自定义对象等其他数据类型来返回多个值。
相关问题
python中return返回多个值
在 Python 中,可以使用元组或列表将多个值返回给调用者。例如:
```
def my_function():
return 1, 2, 3
a, b, c = my_function()
print(a) # 1
print(b) # 2
print(c) # 3
```
或者
```
def my_function():
return [1, 2, 3]
result = my_function()
print(result[0]) # 1
print(result[1]) # 2
print(result[2]) # 3
```
return可以返回多个值吗
在 Python 中,可以使用 return 语句返回多个值,这些值会被打包成一个元组(tuple)类型并返回。例如:
```
def return_multiple_values():
a = 1
b = 2
c = 3
return a, b, c
result = return_multiple_values()
print(result)
```
输出结果为:
```
(1, 2, 3)
```
可以看到,return 语句返回的是一个包含三个元素的元组,这三个元素分别是 a, b, c 的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)