我见过different questions关于在解压相同类型的结构时进行转换。即
def foo():
return ('1', '2')
x, y = foo() # as str
x, y = map(int, foo()) # as int
x, y = [int(n) for n in foo()] # equivalently as int
但假设你有
def foo():
return ('s', '1')
并且您只想解压并转换元组的第二个元素。当然有
x, y = foo()
y = int(y)
为了简单起见,这绝对是最 Pythonic 的方法。但出于好奇,是否有更简洁的方法可以在一行中完成同样的事情?
最佳答案
如果使用Python 3.8+,可以使用赋值表达式:=
def foo():
return ('s', '1')
x, y = (v:=foo())[0], int(v[1])
print(x, y)
打印:
s 1
关于python - 在转换为不同类型时扩展元组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62803652/