Python内联多个变量 [英] Python augmenting multiple variables inline

查看:165
本文介绍了Python内联多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样做

>> x, y = (1, 2)
>> print x, y
1 2

但是扩充会导致语法错误.

But augmenting results in syntax errors..

>> x, y -= (1, 2)
SyntaxError: illegal expression for augmented assignment

我期望有一种不同的方式:

Is there a different way, I was expecting:

>> x, y -= (1, 2)
>> print x, y
0 0

推荐答案

不能在多个目标上使用增强的赋值语句.

You cannot use an augmented assignment statement on multiple targets, no.

引用扩充的作业文档:

除了在单个语句中分配给元组和多个目标外,由扩充赋值语句完成的赋值与普通赋值的处理方式相同.同样,除了可能的就地行为外,增强分配执行的二进制操作与普通的二进制操作相同.

With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.

强调我的.

就地扩展分配从target -= expression转换为target = target.__isub__(expression)(每个运算符具有相应的__i...__钩子),并且不支持将该操作转换为多个目标.

In-place augmented assignment is translated from target -= expression to target = target.__isub__(expression) (with corresponding __i...__ hooks for each operator) and translating that operation to multiple targets is not supported.

在幕后,扩展分配是二进制运算符(+*-等)的特化,不是.因为实现是基于那些运算符的,而二进制运算符只有两个操作数,所以原始目标实施提案.

Under the hood, augmented assignment is a specialisation of the binary operators (+, *, -, etc), not of assignment. Because the implementation is based on those operators and binary operators only ever have two operands, multiple targets were never included in the original implementation proposal.

您只需要简单地分别应用分配即可:

You'll have to simply apply the assignments separately:

x -= 1
y -= 2

,或者,如果您真的想要弄乱,请使用operator模块和zip()operator.isub应用于组合(通过itertools.starmap(),然后使用元组分配:

or, if you really, really wanted to get convoluted, use the operator module and zip() to apply operator.isub to the combinations (via itertools.starmap(), then use tuple assignment:

from operator import sub
from itertools import starmap

x, y = starmap(operator.isub, zip((x, y), (1, 2)))

其中isub将确保调用正确的钩子,从而为支持它的可变类型进行就地减法.

where isub will ensure that the right hook is called allowing for in-place subtraction for mutable types that support it.

或者,如果要处理不支持就地操作的类型,则使用生成器表达式就足够了:

or, if you are manipulating types that don't support in-place manipulation, using a generator expression suffices:

x, y = (val - delta for val, delta in zip((x, y), (1, 2)))

这篇关于Python内联多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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