python函数多个返回值_如何在Python 3中从函数返回多个值

2023-05-16

python函数多个返回值

You can return many values from a function in Python.

您可以从Python中的函数返回许多值。

To achieve this, return a data structure with several values, such as a list of the total number of hours to write every week:

为此,请返回一个具有多个值的数据结构,例如每周要写的总小时数的列表:

def hours_to_write(happy_hours):
   week1 = happy_hours + 2
   week2 = happy_hours + 4
   week3 = happy_hours + 6
   return [week1, week2, week3]
 
print(hours_to_write(4))
# [6, 8, 10]

Python data structures are intended to contain data collections using functions that can be returned.

Python数据结构旨在包含使用可以返回的函数的数据集合。

In this article, we will see how to return multiple values from such data structures — namely dictionaries, lists, and tuples — as well as with a class and data class (Python 3.7+).

在本文中,我们将看到如何从此类数据结构(即字典,列表和元组)以及类和数据类(Python 3.7+)中返回多个值。

1.使用字典 (1. Using a Dictionary)

A dictionary includes combinations of key values inside curly braces ({}). Every item in a dictionary has a key/value combination. An item consists a key and the corresponding value that creates a pair (key:value). Dictionaries are optimized when the key is known to access values.

字典在花括号( {} )中包含键值的组合。 字典中的每个项目都有键/值组合。 一个项目包含一个键和创建一对的对应值( key:value )。 当已知键可访问值时,将优化字典。

Here is a dictionary of people. The name of the person is a key and their age is the corresponding value:

这是人们的字典。 人的名字是关键,年龄是相应的值:

people={
'Robin': 24,
'Odin': 26,
'David': 25
}

This is how to write a function that returns a dictionary with a key/value pair:

这是编写如何返回带有键/值对的字典的函数的方法:

# A Python program to return multiple values using dictionary
# This function returns a dictionary 
def people_age(): 
    d = dict(); 
    d['Jack'] = 30
    d['Kim'] = 28
    d['Bob'] = 27
    return d
d = people_age() 
print(d)
# {'Bob': 27, 'Jack': 30, 'Kim': 28}

2.使用清单 (2. Using a List)

A list is similar to an array of items formed using square brackets, but it is different because it can contain elements of different types. Lists are different from tuples since they are mutable. That means a list can change. Lists are one of Python’s most powerful data structures because lists do not often have to remain similar. A list may include strings, integers, and items. They can even be utilized with stacks as well as queues.

列表与使用方括号形成的项目数组相似,但是有所不同,因为它可以包含不同类型的元素。 列表与元组不同,因为它们是可变的。 这意味着列表可以更改。 列表是Python最强大的数据结构之一,因为列表不必经常保持相似。 列表可以包括字符串,整数和项目。 它们甚至可以与堆栈以及队列一起使用。

# A Python program to return multiple values using list
 
def test(): 
    str1 = "Happy"
    str2 = "Coding"
    return [str1, str2];
 
list = test() 
print(list)
# ['Happy', 'Coding']

Here’s another example. It returns a list that includes natural numbers:

这是另一个例子。 它返回一个包含自然数的列表:

def natural_numbers(numbers = []):
   
   for i in range(1, 16):
       numbers.append(i)
   return numbers
 
print(natural_numbers())
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

3.使用元组 (3. Using a Tuple)

A tuple is an ordered, immutable Python object. Tuples are normally used to store collections of heterogeneous data. Tuples are similar to lists except that they cannot be altered after they are defined. Typically, tuples are quicker than lists. A tuple may be created by separating items with commas: x, y, zor (x, y, z).

元组是有序的,不变的Python对象。 元组通常用于存储异构数据的集合。 元组与列表相似,不同之处在于它们在定义后不能更改。 通常,元组比列表快。 通过用逗号分隔项目x, y, z(x, y, z)可以创建元组。

The following example uses a tuple to store data about an employee (their name, experience in years, and company name):

下面的示例使用一个元组来存储有关员工的数据(他们的姓名,工作年限和公司名称):

Bob = ("Bob", 7, "Google")

Here’s how to write a function that returns a tuple:

这是编写返回元组的函数的方法:

# A Python program to return multiple values using tuple
# This function returns a tuple 
def fun(): 
    str1 = "Happy"
    str2 = "Coding"
    return str1, str2; # we could also write (str1, str2)
str1, str2= fun() 
print(str1) 
print(str2)
# Happy
  Coding

Note that we omitted parentheses in the return statement. The reason is you can return a tuple by separating each item with a comma, as shown in the example above.

请注意,我们在return语句中省略了括号。 原因是您可以通过用逗号分隔每个项目来返回元组,如上面的示例所示。

Keep in mind that the tuple is simply created by the comma — not the parentheses. The parentheses are optional unless you’re using blank tuples or syntactic uncertainty has to be prevented.

请记住,元组仅由逗号而不是括号创建。 除非您使用空白元组或必须避免语法不确定性,否则括号是可选的。

Refer to the official Python 3 documentation for further clarity on tuples.

有关元组的进一步说明,请参阅Python 3官方文档 。

Below is an example of a function that uses parentheses to return a tuple:

以下是使用括号返回元组的函数示例:

def student(name, class):
return (name, class)
print(student("Brayan", 10))
# ('Brayan', 10)

It’s easy to confuse tuples for lists. After all, they are both bags that consist of items. But note the fundamental difference:

混淆元组的列表很容易。 毕竟,它们都是由物品组成的袋子。 但请注意基本区别:

  1. Tuples can’t be altered.

    元组不能更改。
  2. Lists can be altered.

    列表可以更改。

4.使用对象 (4. Using an Object)

This is identical to C/C++ as well as Java. A class (in C, a struct) can be formed to hold several attributes and return a class object:

这与C / C ++和Java相同。 可以形成一个类(在C中为一个结构),以容纳多个属性并返回一个类对象:

# A Python program to return multiple values using class 
class Intro: 
 def __init__(self): 
  self.str1 = "hello"
  self.str2 = "world"
# This function returns an object of Intro
def message(): 
 return Intro() 
 
x = message() 
print(x.str1) 
print(x.str2)
# hello
  world

5.使用数据类(Python 3.7+) (5. Using a Data Class (Python 3.7+))

Using Python 3.7’s data classes, this is how you can return a class with automatically added unique methods, typing, and other useful tools:

使用Python 3.7的数据类,可以通过自动添加的唯一方法,类型和其他有用的工具来返回类:

from dataclasses import dataclass
@dataclass
class Item_list:
    name: str
    perunit_cost: float
    quantity_available: int = 0
    def total_cost(self) -> float:
        return self.perunit_cost * self.quantity_available
    
book = Item_list("better programming.", 50, 2)
x = book.total_cost()
print(x)
print(book)
# 100
  Item_list(name='better programming.', perunit_cost=50, 
  quantity_available=2)

See the official documentation for further clarity on data classes.

有关数据类的进一步说明,请参见官方文档 。

关键要点 (The Key Takeaway)

The primary objective of this article is to help you return several values from a Python function. As we have seen, there are numerous methods you can use to achieve that.

本文的主要目的是帮助您从Python函数返回几个值。 如我们所见,可以使用多种方法来实现这一目标。

The most crucial point is that you need to learn concepts and develop your programming skills.

最关键的一点是,您需要学习概念并发展编程技能。

Thanks for reading.

谢谢阅读。

翻译自: https://medium.com/better-programming/how-to-return-multiple-values-from-a-function-in-python-3-ddb131279cd

python函数多个返回值

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python函数多个返回值_如何在Python 3中从函数返回多个值 的相关文章

  • STM32和Linux(转载)

    Linux和stm32 一个是软件平台一个是硬件平台 xff0c 完全不一样的 xff08 记住 xff0c 是平台 xff01 xff09 这样说吧 xff0c 既然你喜欢单片机 xff0c 就先学stm32 xff0c 把硬件基础打牢
  • PX4飞控问题之参数重置问题

    PX4在上电的时候会出现参数重置的问题 xff0c 出现这个问题的机率很小 xff0c 可能上电几千甚至上万次才会出现一次重置的情况 xff0c 但一旦出现了参数重置 xff0c 飞机就无法飞行 xff0c 得重新校准传感器 要解决这个问题
  • STM32硬件基础--LTDC显示图像

    STM32硬件基础 LTDC显示图像 海东青电子 2019 11 13 23 40 05字数 2 635阅读 3 102 海东青电子原创文章 xff0c 转载请注明出处 xff1a https www jianshu com p 21638
  • PX4轨迹生成公式推导

    PX4轨迹生成公式推导下载链接 对于多旋翼 飞行任务的时候 通过地面站画出航点 上传给飞控 飞控通过轨迹生成算法生成平滑的目标位置 速度及加速度 给位置控制模块控制飞机的位置 速度及加速度 PX4轨迹生成的方法为 约束加加速度的S型速度曲线
  • 植保无人机航线规划

    最近折腾了植保无人机航线规划的算法 支持任意多边形 不包括自相交多边形 的边界及障碍区域 其中涉及到了多边形内缩外扩 多边形的分解 多边形交集 并集 差集 深度优先搜索 最短路径算法 耗时两个多月 用C 实现整套算法 生成的库在missio
  • 现代控制工程笔记(一)控制系统的状态空间描述

    文章目录 1 基本概念2 系统的状态空间描述状态空间描述框图状态变量选取的非唯一性 3 由系统微分方程列写状态空间表达式一 微分方程中不包含输入函数的导数项相变量法其他方法 xff1a 二 微分方程中包含输入函数的导数项 4 由传递函数列写
  • 百度Apollo 2.0 车辆控制算法之LQR控制算法解读

    百度Apollo 2 0 车辆控制算法之LQR控制算法解读 Apollo 中横向控制的LQR控制算法在Latcontroller cc 中实现 根据车辆的二自由度动力学模型 1 根据魔术公式在小角度偏角的情况下有 轮胎的侧向力与轮胎的偏离角
  • 多传感器融合--MATLAB跟踪器介绍

    多传感器融合 MATLAB跟踪器介绍 MATLAB通过多目标跟踪器可以融合多传感器检测到的目标信息 xff0c 常用到的多目标跟踪器有trackerGNN trackerJPDA trackerTOMHT trackerPHD等 track
  • MATLAB多传感器融合--核心步骤

    MATLAB多传感器融合 核心步骤 MATLAB的多传感器融合的核心步骤在stepImpl函数中实现 xff0c 该函数的输入的跟踪目标和测量的目标的信息 xff0c 输出为证实的真目标信息和处于试探的跟踪目标信息 confirmedTra
  • [新手编译内核]kernel进行编译时提示No rule to make target `menconfig'.

    windows下下载了 linux 2 6 37内核源码 xff0c 拷贝到U盘上 xff0c 通过mount挂载到了虚拟机里的Centos 5 5系统上 通过putty使用host only方式连接到虚拟机 xff0c 进行操作 在 mn
  • 协议和协议栈的区别?

    在通信领域特别是无线通信领域 xff0c 我们经常会听到用到什么协议啊 xff0c 什么协议栈方面的东西 1 首先 xff0c 协议定义的是一些列的通信标注 xff0c 通信的双方需要共同按照这一个标准进行正常的数据收发 xff1b 在计算
  • linux-kernel, bus总线数据结构分析

    设备模型中的三大组件是 xff1a 总线 xff0c 驱动 xff0c 设备 bus driver device 数据结构总览 总线除了一些物理总线的抽象 xff0c 还代表一些虚拟的总线 xff0c 如platform xff0c 所以在
  • JavaScript 猜数字小游戏

    说明 单独创建一个js文件 然后在文件里面写入下列代码 之后在html页面引入该js文件即可 span class token comment 设计并实现 猜数游戏 xff0c 并输出每轮猜数游戏的猜测次数 游戏规则如下 xff1a spa
  • 纯干货:LCD屏和OLED屏的区别?手机屏幕材质各有什么区别?

    纯干货 xff1a LCD屏和OLED屏的区别 xff1f 手机屏幕材质各有什么区别 xff1f 慢慢买比价 已认证的官方帐号 74 人赞同了该文章 今天我就为大家带来一篇纯干货知识点整理 xff0c 关于手机屏幕那点事看完秒懂 以及大家对
  • OpenJDK在OpenHarmony上异常问题分析

    目录 0 前言1 问题日志打印2 报错日志代码分析3 问题解决方案 0 前言 基于OpenHarmony的2022 06 30 master之前版本OpenJDK测试OK xff0c 但是之后版本测试报异常错误 1 问题日志打印 2 报错日
  • vnc viewer远程连接xfce桌面无法打开terminal终端

    这是因为默认的terminal错啦 xff0c 改一下就好 在页面左上角上找到 Appication gt Settings gt Settings Manager gt Preferred Applications gt Utilitie
  • ucosii第一章读书笔记

    第一章 嵌入式操作系统 1 1 计算机操作系统 简介 xff1a 嵌入式操作系统属于操作系统的一种 嵌入式操作系统的概念 xff1a 应用于嵌入式系统的操作系统叫做嵌入式操作系统 操作系统的概念 xff1a 是一种系统软件 作用于硬件和应用
  • ceres中的loss函数实现探查,包括Huber,Cauchy,Tolerant图像实现及源码

    ceres中的loss函数实现探查 xff0c 包括Huber xff0c Cauchy xff0c Tolerant图像实现及源码 各个损失函数的趋势图 xff1a Ceres内嵌的loss functions原理 xff1a 以Cauc
  • 使用自己的INDEMIND相机来运行ORBSLAM2单目,双目和深度模式(小觅相机和realsense通用)

    流程一览 配置ROSROS环境准备 以 xff11 6 04 ROS Kinetic为例 创建自己的工作空间 配置ORBSLAM编译ORBSLAM2 ROS常见错误及解决运行build ros sh时出现问题一 运行build ros sh
  • 超详细中文车牌识别开源库EasyPR入门实战(win10_VS2019_opencv34)

    中文车牌识别库EasyPR配置全过程及编译问题解决 xff08 win10 VS2019 opencv34 xff09 本文目录 中文车牌识别库EasyPR配置全过程及编译问题解决 xff08 win10 VS2019 opencv34 x

随机推荐