如何从函数中存储第二个返回值?

发布于 2025-01-30 19:02:23 字数 420 浏览 4 评论 0原文

有没有办法仅存储函数中的第二个返回值?我正在寻找这样的东西:

def func(pos, times_clicked, cost):
    if buy_image_rect.collidepoint(pos) and times_clicked >= cost:
        times_clicked -= cost
        cost += 5
    return cost, times_clicked

# But I want to get the second return value for times_clicked. It doesn't work like this:
times_clicked = func(event.pos, times_clicked, cost) 

我需要为不同事物获得两个回报值。请帮忙!

Is there a way to store only the second return value from a function? Im looking for something like this:

def func(pos, times_clicked, cost):
    if buy_image_rect.collidepoint(pos) and times_clicked >= cost:
        times_clicked -= cost
        cost += 5
    return cost, times_clicked

# But I want to get the second return value for times_clicked. It doesn't work like this:
times_clicked = func(event.pos, times_clicked, cost) 

I need to get both of the return values for different things. Please help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

晒暮凉 2025-02-06 19:02:24

返回值是带有两个组件的元组。将结果分配给两个单独的变量:

cost, times_clicked = func(event.pos, times_clicked, cost) 

The return value is a tuple with two components. Assign the result to two separate variables:

cost, times_clicked = func(event.pos, times_clicked, cost) 
疾风者 2025-02-06 19:02:24

times_clicked实际上保留了两个值。

当您从函数返回一些值时,返回元组。

您的元组可以分布成这样的变量:

var_1, var_2 = (1, 2) # var_1 == 1, var_2 == 2

调用返回两个值的函数时相同的变量:

cost, times_clicked = func(event.pos, times_clicked, cost) 

times_clicked actually holds both values.

When you return a few values from a function a tuple is returned.

You tuple can be spread into variables like that:

var_1, var_2 = (1, 2) # var_1 == 1, var_2 == 2

Same when you call a function that returns two values:

cost, times_clicked = func(event.pos, times_clicked, cost) 
罗罗贝儿 2025-02-06 19:02:24

当调用函数时,具有多个变量的函数的返回值将返回带有值的元组。

要访问值,请参考元组的索引号,与函数中分配的返回值的顺序相对应。

tup= func(event.pos, times_clicked, cost)
cost, times_clicked= tup #(var1,var2)

The return value of a function with more than one variable would return a tuple with the values when the function is called.

To access the values, by referring to the index number of the tuple corresponding to the order of return values assigned in the function.

tup= func(event.pos, times_clicked, cost)
cost, times_clicked= tup #(var1,var2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文