[英]Function returns returns either int or list of ints. Assinging the first to a variable
Suppose we have 假设我们有
def f_1():
return (3, 4)
def f_2():
return 2
The functions are given. 给出了功能。 It is not code that I can modify. 我无法修改的代码。 We know they return either an integer or a sequence of them. 我们知道它们返回的是整数或序列。
I would like to assign the return to a variable, where the variable should take only the first of the integers if the return is a sequence of them. 我想将return分配给一个变量,如果return是它们的序列,则该变量应仅取整数的第一个。
Is there a build-in syntactic device in Python that allows me to do this? 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
Note: Assume that we don't know which of the functions return the sequence and which return just a number. 注意:假设我们不知道哪个函数返回序列,哪个函数仅返回数字。
Is there a build-in syntactic device 有内置的句法设备吗
No. The usual practice is to ask for forgivness : 不,通常的做法是请求 宽恕 :
x = function()
try:
x = x[0]
except TypeError:
pass
I wouldnt go for try-except statement. 我不会去尝试-除外声明。 To me it's an overkill. 对我来说,这太过分了。
More likely I would try to do something like: 我更有可能尝试执行以下操作:
result = function()
# this can be changed to abc.Sequence for more general approach
if isinstance(result, (list, tuple)):
result = result[0]
Going in the other direction, wrap f_2
in another function to ensure that the function called in the body of the loop always returns a sequence. 在另一个方向上,将f_2
包装在另一个函数中,以确保在循环主体中调用的函数始终返回序列。
for function in [f_1, lambda : (f_2(),)]:
x = function()[0]
The additional overhead of another function call may make this approach undesirable. 另一个函数调用的额外开销可能会使这种方法不受欢迎。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.