为什么在交换之前而不是内联中查找索引会改变结果? [英] Why does looking up an index *before* a swap rather than inline change the result?

查看:77
本文介绍了为什么在交换之前而不是内联中查找索引会改变结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

data1 = [1.48,  -4.96]
data2 = [1.48,  -4.96]

# i is index we want to swap; mn is the data we want to swap the content of index-i with
i = 0; mn = data[1]

# attempt 1: prior lookup
k = data1.index(mn)
data1[i], data1[k] = data1[k], data1[i]

# attempt 2: in-line lookup
data2[i], data2[data2.index(mn)] = data2[data2.index(mn)], data2[i]

print("Prior lookup:  %r" % data1)
print("Inline lookup: %r" % data2)

输出为:

Prior lookup:  [-4.96, 1.48]
Inline lookup: [1.48, -4.96]

为什么这些不一样?

推荐答案

让我们添加一些跟踪信息,以便我们可以看到操作顺序:

Let's add some tracing so we can see order-of-operations:

import sys

def findIdx(ary, tgt):
    retval = ary.index(tgt)
    print('First instance of %r in %r is at position %r' % (tgt, ary, retval), file=sys.stderr)
    return retval

data1 = [1.48,  -4.96]
i = 0
mn = data1[1]

k = findIdx(data1, mn)
data1[i], data1[k] = data1[k], data1[i]
print("Prior lookup:  %r" % data1)

data2 = [1.48,  -4.96]
data2[i], data2[findIdx(data2, mn)] = data2[findIdx(data2, mn)], data2[i]
print("Inline lookup: %r" % data2)

然后说明日志:

First instance of -4.96 in [1.48, -4.96] is at position 1
Prior lookup:  [-4.96, 1.48]
First instance of -4.96 in [1.48, -4.96] is at position 1
First instance of -4.96 in [-4.96, -4.96] is at position 0
Inline lookup: [1.48, -4.96]

如您所见,对索引的最后一次调用是针对已经替换了两个元素之一的数组 .

As you can see, the last call to lookup the index is doing so against an array that has already had one of its two elements replaced.

这篇关于为什么在交换之前而不是内联中查找索引会改变结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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