Return несколько переменных python

Alternatives for returning multiple values from a Python function [closed]

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Option: Using a tuple

def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0, y1, y2) 

However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It’s also rather ugly to unpack them wherever you want to receive them.

Option: Using a dictionary

The next logical step seems to be to introduce some sort of ‘record notation’. In Python, the obvious way to do this is by means of a dict . Consider the following:

def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return

(Just to be clear, y0, y1, and y2 are just meant as abstract identifiers. As pointed out, in practice you’d use meaningful identifiers.) Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,

Option: Using a class

However, there is another option. We could instead return a specialized structure. I’ve framed this in the context of Python, but I’m sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:

class ReturnValue: def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) 

In Python the previous two are perhaps very similar in terms of plumbing — after all < y0, y1, y2 >just end up being entries in the internal __dict__ of the ReturnValue . There is one additional feature provided by Python though for tiny objects, the __slots__ attribute. The class could be expressed as:

class ReturnValue(object): __slots__ = ["y0", "y1", "y2"] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 

The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

Option: Using a dataclass (Python 3.7+)

Using Python 3.7’s new dataclasses, return a class with automatically added special methods, typing and other useful tools:

@dataclass class Returnvalue: y0: int y1: float y3: int def total_cost(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) 

Option: Using a list

def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result 

This is my least favorite method though. I suppose I’m tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn’t gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are mutable, whereas tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.

Источник

Читайте также:  Php сделать массив ассоциативным

Как вернуть сразу несколько значений из функции в Python 3

Сегодня мы делимся с вами переводом статьи, которую нашли на сайте medium.com. Автор, Vivek Coder, рассказывает о способах возврата значений из функции в Python и объясняет, как можно отличить друг от друга разные структуры данных.

Фото с сайта Unsplash. Автор: Vipul Jha

Python удобен в том числе тем, что позволяет одновременно возвращать из функции сразу несколько значений. Для этого нужно воспользоваться оператором return и вернуть структуру данных с несколькими значениями — например, список общего количества рабочих часов за каждую неделю.

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 используются для хранения коллекций данных, которые могут быть возвращены посредством оператора return . В этой статье мы рассмотрим способы возврата нескольких значений с помощью подобных структур (словарей, списков и кортежей), а также с помощью классов и классов данных (Python 3.7+).

Способ 1: возврат значений с помощью словарей

Словари содержат комбинации элементов, которые представляют собой пары «ключ — значение» ( key:value ), заключенные в фигурные скобки ( <> ).

Словари, на мой взгляд, это оптимальный вариант для работы, если вы знаете ключ для доступа к значениям. Далее представлен словарь, где ключом является имя человека, а соответствующим значением — возраст.

А теперь перейдем к функции, которая возвращает словарь с парами «ключ — значение».

# 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) #

Способ 2: возврат значений с помощью списков

Списки похожи на массивы, сформированные с использованием квадратных скобок, однако они могут содержать элементы разных типов. Списки также отличаются от кортежей, поскольку являются изменяемым типом данных. То есть любой список может меняться.

Списки — одна из наиболее универсальных структур данных в 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']

Вот пример, где возвращается список с натуральными числами.

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: возврат значений с помощью кортежей

Кортежи — это упорядоченные неизменяемые объекты в Python, которые обычно используются для хранения коллекций неоднородных данных.

Читайте также:  If and else condition in javascript

Кортежи напоминают списки, однако их нельзя изменить после того, как они были объявлены. А еще, как правило, кортежи быстрее в работе, чем списки. Кортеж можно создать, отделив элементы запятыми: x, y, z или (x, y, z) .

На этом примере кортеж используется для хранения данных о сотруднике (имя, опыт работы в годах и название компании).

А вот пример написания функции для возврата кортежа.

# 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

Обратите внимание: мы опустили круглые скобки в операторе return , поскольку для возврата кортежа достаточно просто отделить каждый элемент запятой (как показано выше).

Не забывайте, что кортеж можно создать с помощью запятой вместо круглых скобок. Круглые скобки требуются только в тех случаях, когда используются пустые кортежи или вам нужно избежать синтаксической неточности.

Чтобы лучше разобраться в кортежах, обратитесь к официальной документации Python 3 (документация приведена на английском языке. — Прим. ред.).

Ниже показан пример функции, которая использует для возврата кортежа круглые скобки.

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

Повторюсь, кортежи легко перепутать со списками (в конце концов, и те, и другие представляют собой контейнер, состоящий из элементов). Однако нужно помнить о фундаментальном различии: кортежи изменить нельзя, а списки — можно.

Способ 4: возврат значений с помощью объектов

Тут все так же, как в 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+)

Классы данных в Python 3.7+ как раз помогают вернуть класс с автоматически добавленными уникальными методами, модулем typing и другими полезными инструментами.

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)

Чтобы лучше разобраться в классах данных, обратитесь к официальной документации Python 3 (документация приведена на английском языке. — Прим. ред.).

Вывод

Цель этой статьи — ознакомить вас со способами возврата нескольких значений из функции в Python. И, как вы видите, этих способов действительно много.

Учите матчасть и постоянно развивайте свои навыки программирования. Спасибо за внимание!

Читайте также:  Css img table cell

Источник

How can I return two values from a function in Python?

And I want to be able to use these values separately. When I tried to use return i, card , it returns a tuple and this is not what I want.

Please provide an example of calling this expected function and using its return value(s), so that it makes clear why you don’t want tuples.

8 Answers 8

You cannot return two values, but you can return a tuple or a list and unpack it after the call:

def select_choice(): . return i, card # or [i, card] my_i, my_card = select_choice() 

On line return i, card i, card means creating a tuple. You can also use parenthesis like return (i, card) , but tuples are created by comma, so parens are not mandatory. But you can use parens to make your code more readable or to split the tuple over multiple lines. The same applies to line my_i, my_card = select_choice() .

If you want to return more than two values, consider using a named tuple. It will allow the caller of the function to access fields of the returned value by name, which is more readable. You can still access items of the tuple by index. For example in Schema.loads method Marshmallow framework returns a UnmarshalResult which is a namedtuple . So you can do:

data, errors = MySchema.loads(request.json()) if errors: . 
result = MySchema.loads(request.json()) if result.errors: . else: # use `result.data` 

In other cases you may return a dict from your function:

def select_choice(): . return

But you might want consider to return an instance of a utility class (or a Pydantic/dataclass model instance), which wraps your data:

class ChoiceData(): def __init__(self, i, card, other_field, . ): # you can put here some validation logic self.i = i self.card = card self.other_field = other_field . def select_choice(): . return ChoiceData(i, card, other_field, . ) choice_data = select_choice() print(choice_data.i, choice_data.card) 

I would like to return two values from a function in two separate variables.

What would you expect it to look like on the calling end? You can’t write a = select_choice(); b = select_choice() because that would call the function twice.

Values aren’t returned «in variables»; that’s not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you’re doing is giving the received value a name in the calling context. The function doesn’t put the value «into a variable» for you, the assignment does (never mind that the variable isn’t «storage» for the value, but again, just a name).

When i tried to to use return i, card , it returns a tuple and this is not what i want.

Actually, it’s exactly what you want. All you have to do is take the tuple apart again.

And i want to be able to use these values separately.

So just grab the values out of the tuple .

The easiest way to do this is by unpacking:

Источник

Оцените статью