我可以按以下方式进行任务分解:
a, b = s.split(' ', 1)
对于具有多个单词的字符串s
。
我们如何在if
或elif
中进行相同的操作,并使用Python 3.8中引入的最新赋值表达式(可以有多个目标)?
我尝试过:
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.
我收到以下错误:
elif (a, b := s.split(' ', 1)) and some_func(a) and some_func(b):
NameError: name 'a' is not defined
我想要这个的原因是,如果我的第一个条件得到满足,我不想不必要地分割字符串。
请参阅有关将问题重新分配给元组的评论。我绝对不是专家。发布以下内容是因为它可行,我认为这可能对您足够?基本上,将元组保存到一个有效的变量中,然后可以对其进行索引
if some_thing:
# some code.
elif (split := s.split(' ', 1)):
if some_func(split[0]) and some_func(split[1]):
# some code probably using a and b as well.