交换列表中的项目时出现奇怪的行为

时间:2018-07-18 04:04:57

标签: python python-2.7 list swap

我正在尝试在python代码中执行交换。我有一个包含唯一标签的列表,如下所示:

list = [0, 1, ...., N-1]

交换发生在两个如下所示的for循环中(一个为奇数,一个为偶数):

if odd:
    for exch in range(0, N / 2 -1 + N%2):
        index1 = list[2*exch+1]
        index2 = list[2*exch+2]
        some_conditions = function(index1, index2)
        print 'Trying to swap indexes ' + str(index1) + ' and ' + str(index2)
        if np.random.uniform(0,1) < some_conditions:
            list[index1], list[index2] = list[index2], list[index1]
            other[index1], other[index2] = other[index2], other[index1]
else:
    for exch in range(0, N / 2 ):
        index1 = list[2*exch]
        index2 = list[2*exch+1]
        some_conditions = function(index1, index2)
        print 'Trying to swap indexes ' + str(index1) + ' and ' + str(index2)
        if np.random.uniform(0,1) < some_conditions:
            list[index1], list[index2] = list[index2], list[index1]
            other[index1], other[index2] = other[index2], other[index1]    

以某种方式,当发生交换时,python连续两次打印相同的索引,并报告类似的信息(对于偶数和奇数都是如此):

Trying to swap index 0 and index 1
Trying to swap index 0 and index 4

鉴于index1和index2的值是唯一的,python如何打印这样的内容?在随后的步骤中,不会将值0重印两次,因此在内存中可能没问题,但是我无法弄清楚为什么它会打印两次相同的索引。

我在这里想念什么吗?作为参考,这是MPI上分子动力学的副本交换计算,但交换仅在等级0上进行。这是在python 2.7上进行的。

编辑:更新了带有奇数和偶数互换的描述,使内容更清晰。我之所以有这种“怪异”的原因是,我需要交换与其他列表相对应的值,这些值与某些模拟参数相对应。例如,如果其他包含:

other = [2, 3, 1, 4, 5]

我会尝试将1与2交换为3,将3与4交换为奇数交换,然后再进行偶数交换,请尝试将2与3和4与5交换。

1 个答案:

答案 0 :(得分:3)

您在这里做的事情很奇怪。首先,将index1和index2声明为列表内的值,而不是实际的索引。

index1 = list[2*exch+1]
index2 = list[2*exch+2]

然后,当您说

list[index1], list[index2] = list[index2], list[index1]

您实际上是使用index1和index2作为索引,当它们不是实际索引时,它们是列表中的值,因此,例如,首先index1将为0,index2将为1,然后交换它们,第二次index1将是您存储在list [3]中的任何值,而index2将是您在list [4]中存储的值。

这将解决此问题,因为您实际上不需要存储值即可更改它们

for exch in range(0, N / 2 -1 + N%2):
index1 = 2*exch+1
index2 = 2*exch+2
some_conditions = function(index1, index2)
print 'Trying to swap indexes ' + str(index1) + ' and ' + str(index2)
if np.random.uniform(0,1) < some_conditions:
    list[index1], list[index2] = list[index2], list[index1]