swap函数python,python a,b = b,一个实现?它与C ++交换函数有何不同?

I am not sure why a[0], a[a[0]] = a[a[0]], a[0] this one does not do the swap?

>>> nums

[2, 1, 0]

>>> a = [2,1,0]

>>> a[0], a[a[0]] = a[a[0]], a[0]

>>> a

[2, 1, 0]

>>> a[0]

2

>>> a[0],a[2] = a[2], a[0]

>>> a

[0, 1, 2]

My guess is that the implementation of a, b = b, a syntax is something like:

tmp = a[0] (tmp = 2)

a[0] = a[a[0]] (a[0] = a[2] = 0)

a[a[0]] = tmp (a[a[0]] = a[0] = tmp = 2)

Then I checked the implementation of swap function in C++. I know nothing about C++, but it looks like the idea is the same

:

http://www.cplusplus.com/reference/algorithm/swap/

The behavior of these function templates is equivalent to:

template void swap (T& a, T& b)

{

T c(std::move(a)); a=std::move(b); b=std::move(c);

}

template void swap (T (&a)[N], T (&b)[N])

{

for (size_t i = 0; i

}

we have c = a, then a = b and b = a

So why C++ swap function does not have this problem?

And how to write this kind of swap function in a pythonic way?

解决方案

This kind of the behaviour is indeed related to the way Python evaluates the expression of the type

a,b=b,a

In fact, what Python does is first it "prepares" the values of the right side by creating a tuple (b,a). Then this tuple is unpacked and assigned to the variables in the reverse order.

It is important to note that although Python uses references to objects the objects the variable names refer to may change if they refer to values of immutable type. It is not so with mutable types (illustrated by example in Python FAQ).

To break down the example with mutable types (lists) that you used:

a = [2,1,0]

a[0], a[a[0]] = a[a[0]], a[0]

a[a[0]] takes the value from the a[0] element (equal to 2) of the list a (value 0).

a[0] is 2 hence the tuple created is (0,2)

Tuple (0,2) is unpacked and 0 replaces 2 in the list (0th element).

Now, a[a[0]] can be read as: take 0th element of list a (which is currently 0) and then replace the value in the list at that place with 2 from tuple unpacking (now 0 is replaced by 2 - which make the operation look like it does nothing to the list).

As suggested in the answer from von Oak changing the order helps because the step from the point 4. above does not replace the value again.

I suggest you refer to passing by assignment answer to understand functions and parameter passing.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值