相关疑难解决方法(0)

如何使用 Python 中的 walrus 运算符执行赋值解构

我可以做一个赋值解构:

a, b = s.split(' ', 1)
Run Code Online (Sandbox Code Playgroud)

对于s包含多个单词的字符串。

我们如何使用 Python 3.8 中引入的最新赋值表达式(是否可能有多个目标)在 an ifor 中做同样的事情elif

我试过:

if some_thing:
    # some code.
elif (a, b := s.split(' ', 1)) and some_func(a) and some_func(b):
    # some code probably using a and b as well.
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

elif (a, b := s.split(' ', 1)) and some_func(a) and some_func(b):
NameError: name 'a' is not defined
Run Code Online (Sandbox Code Playgroud)

我想要这个的原因是因为如果我的第一个条件得到满足,我不想不必要地拆分我的字符串。

python destructuring python-3.x python-3.8

7
推荐指数
2
解决办法
685
查看次数

标签 统计

destructuring ×1

python ×1

python-3.8 ×1

python-3.x ×1