如何在Python中使用walrus运算符执行分配分解 [英] How to perform assignment destructuring using the walrus operator in Python

查看:58
本文介绍了如何在Python中使用walrus运算符执行分配分解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以按以下方式进行作业分解:

I can do an assignment destructuring as:

a, b = s.split(' ', 1)

包含一个以上单词的字符串 s .

for a string s which has more than one word.

如何使用最新的赋值表达式对 if elif 进行操作是python 3.8中引入的(可以有多个目标)吗?

How can we do the same in, say an if or elif, with the latest assignment expression introduced in Python 3.8 (is it possible to have multiple targets) ?

我尝试过:

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

我想要这样做的原因是因为我不想在满足第一个条件的情况下不必要地分割字符串.

The reason I want this is because I don't want to split my string unnecessarily if my first condition is satisfied.

推荐答案

请参阅有关将问题重新分配给元组的评论.我绝对不是专家.发布以下内容是因为它可以正常工作,我认为它可能对您足够好?基本上,将元组保存到一个有效的变量中,然后可以对其进行索引

See comment on question re assigning to a tuple. I'm by no means an expert though. Posting the below because it works and I think it may be good enough for you? Basically, save the tuple to one variable, which works, and then you can index it

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.

这篇关于如何在Python中使用walrus运算符执行分配分解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆