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

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函数多个返回值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值