返回多个值并且在 Python 中只使用一个
Return multiple values and only use One in Python
要从一个函数返回多个值并且只使用一个值:
- 使用括号调用函数。
- 使用方括号访问特定索引处的值。
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
0
,最后一个元素的索引为-1
或len(collection) - 1
。如果您尝试访问超出范围的索引处的集合,您将得到一个
IndexError
.
You can use a try/except
statement if you need to handle the error.
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.
def my_func(): return 'one', 'two', 'three' _, second, _ = my_func() print(second) # 👉️ 'two'
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.
def my_func(): return 'one', 'two', 'three' first, *_ = my_func() print(first) # 👉️ 'one' print(_) # 👉️ ['two', 'three']
*可迭代解包运算符
使我们能够在函数调用、理解、生成器表达式和分配给变量时解包可迭代对象。
下划线_
变量存储函数在第一个值之后返回的所有值。