gpt4 book ai didi

python - 函数返回返回 int 或 int 列表。将第一个赋值给一个变量

转载 作者:太空宇宙 更新时间:2023-11-04 10:07:12 27 4
gpt4 key购买 nike

假设我们有

def f_1():
return (3, 4)

def f_2():
return 2

给出了函数。这不是我可以修改的代码。我们知道它们返回一个整数或它们的序列。

我想将返回值分配给一个变量,如果返回值是整数的序列,则变量应该只取第一个整数。

Python 中是否有内置的句法设备允许我执行此操作?

for function in [f_1, f_2]:
...
x = function()[0] # Works for f_1, breaks for f_2
y = function() # Works for f_2, assigns (3, 4) for f_1 while
# we really would like only the 3 to be the
# assigned value

注意:假设我们不知道哪些函数返回序列,哪些只返回一个数字。

最佳答案

Is there a build-in syntactic device

没有。通常的做法是ask对于 forgivness :

x = function()
try:
x = x[0]
except TypeError:
pass

关于python - 函数返回返回 int 或 int 列表。将第一个赋值给一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40385777/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com