返回多个值并且在 Python 中只使用一个

返回多个值并且在 Python 中只使用一个

Return multiple values and only use One in Python

要从一个函数返回多个值并且只使用一个值:

  1. 使用括号调用函数。
  2. 使用方括号访问特定索引处的值。
主程序
def my_func(): return 'one', 'two', 'three' # ✅ Return multiple values from a function and only use one first = my_func()[0] print(first) # 👉️ 'one second = my_func()[1] print(second) # 👉️ 'two' third = my_func()[2] print(third) # 👉️ 'three' # ---------------------------- _, second, _ = my_func() print(second) # 👉️ 'two' # ---------------------------- first, *_ = my_func() print(first) # 👉️ 'one'

确保在访问特定索引处的值之前使用括号调用函数。

主程序
def my_func(): return 'one', 'two', 'three' first = my_func()[0] print(first) # 👉️ 'one
Python 索引是从零开始的,因此集合(例如列表或元组)中的第一个元素的索引为0,最后一个元素的索引为-1len(collection) - 1

如果您尝试访问超出范围的索引处的集合,您将得到一个
IndexError.

You can use a try/except statement if you need to handle the error.

main.py
def my_func(): return 'one', 'two', 'three' try: first = my_func()[100] print(first) # 👉️ 'one except IndexError: pass

The specified index is out of range, so the except block runs.

Alternatively, you can use unpacking to only use one of the multiple returned
values from a function.

main.py
def my_func(): return 'one', 'two', 'three' _, second, _ = my_func() print(second) # 👉️ 'two'
When unpacking, make sure to declare exactly as many variables as there are items in the iterable.

When unpacking from a tuple or list, each variable declaration counts for a
single item.

Make sure to declare exactly as many variables as there are items in the tuple
or list.

You can use underscores for the values you are not interested in.

If you try to unpack more or fewer values than there are in the collection, you
would get an error.

You can also use the iterable unpacking operator to store the rest of the items
after you have assigned the one value you need to a variable.

main.py
def my_func(): return 'one', 'two', 'three' first, *_ = my_func() print(first) # 👉️ 'one' print(_) # 👉️ ['two', 'three']

*迭代解包运算符
使我们能够在函数调用、理解、生成器表达式和分配给变量时解包可迭代对象。

下划线_变量存储函数在第一个值之后返回的所有值。