Python内联多个变量

编程入门 行业动态 更新时间:2024-10-26 19:32:57
本文介绍了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内联多个变量

本文发布于:2023-11-14 03:09:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586053.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   内联   变量   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!