gpt4 book ai didi

python - 在 Python 中交换表达式中的表达式(交换三个及更多 var)

转载 作者:行者123 更新时间:2023-11-28 22:11:45 26 4
gpt4 key购买 nike

我尝试在 Python 中分配三个表达式,但结果出乎意料。

让我们从简单的交换开始。你可能知道这个作业的结果:

A = [10, 11, 12]
p = 0
A[p + 1], A[p] = A[p], A[p + 1] # <--
print(A)

结果是(如预期的那样):

[11, 10, 12]

现在我想更大胆一点,所以尝试了这个作业:

A = [10, 11, 12]
p = 0
p, A[p + 1], A[p] = p + 1, A[p], A[p + 1] # <--
print(A)

我以为结果会是:

[10, 12, 11]

然而,结果是:

[10, 11, 10]

这是出乎意料的!

我读了Python documentation regarding assignments :

Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2]:

x = [0, 1]
i = 0
i, x[i] = 1, 2 # i is updated, then x[i] is updated
print(x)

我的交换没有得到类似的结果。我不明白交换背后的逻辑。怎么回事?

最佳答案

您可以将其视为使用临时变量从左到右连续赋值的简写:

p, A[p + 1], A[p] = p + 1, A[p], A[p + 1]

相当于

temp1  = p + 1  # 1
temp2 = A[p] # 10 (A[0])
temp3 = A[p+1] # 11 (A[1])
p = temp1 # p = 1
A[p+1] = temp2 # A[2] = 10
A[p] = temp3 # A[1] = 11

所以 A = [10,11,10]

如果您将 p 放在列表的末尾,您可能会更接近您的预期结果:

A[p + 1], A[p], p = A[p], A[p + 1], p + 1

A is now [11,10,12]
P is now 1

换句话说,后自增是可以的,但前自增在这种场景下是行不通的(源数据中使用了前自增索引)

您可以通过手动计算源数据中的偏移量来实现,但这有点违反直觉:

p, A[p+1], A[p] = p+1, A[p+1], A[p+2]

关于python - 在 Python 中交换表达式中的表达式(交换三个及更多 var),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55477851/

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