gpt4 book ai didi

python - 将 python 的就地加法与解压缩的元组一起使用

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:54 24 4
gpt4 key购买 nike

python 在解包元组时无法执行就地添加操作是否有原因,是否有解决此问题的简单方法?

例如

>>> x, y = (5, 0)
>>> x, y += (1, 8)
SyntaxError: illegal expression for augmented assignment

备选方案很丑陋,而且对于代码维护来说不是很明显:

>>> x, y = (5, 0)
>>> x, y = map(sum, zip((x, y), (1, 8)))

最佳答案

如果你总是有两个部分,你可以使用复杂的文字来表示这对值(所以 x 将是实部,而 y 是虚部):

>>> x_y = 5 + 0j
>>> x_y += 1 + 8j
>>> x_y.real, x_y.imag
(6.0, 8.0)

显然,当您只执行一个操作时,这看起来有点复杂 (!),但如果您使用大量成对的值,它会工作得很好。然而,它被认为是一种 hack 并且会降低您的代码的可读性(人们可能想知道 .real.imag 在做什么)。


更好的选择是构建您自己的 numeric type来保存相关的值。例如:

>>> from collections import namedtuple
>>> class XY(namedtuple('XY', 'x y')):
def __repr__(self):
return 'XY({0.x!r}, {0.y!r})'.format(self)
def __add__(self, other):
return XY(self.x + other.x, self.y + other.y)


>>> xy = XY(5, 0)
>>> xy += XY(1, 8)
>>> xy
XY(6, 8)

这对于适应更大的数字组来说更具可读性和灵 active ,而复数只能包含两个值。通过微小的调整,XY.__add__ 也可以接受任何长度为 2 的可迭代对象,例如xy += (1, 8) 也可以。


关于为什么您最初的尝试不起作用,请注意 the augmented assignment documentation指出(强调我的):

An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.

关于python - 将 python 的就地加法与解压缩的元组一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31588232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com