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

2024-06-02 07:15:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在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上。这是在Python2.7上实现的。你知道吗

编辑:更新了奇偶交换的描述,使事情更清楚一些。我之所以有这个“奇怪”的东西,是因为我需要交换其他列表中相邻的值,这些值对应于一些模拟参数。例如,如果其他包含:

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

我试着用2换1,用4换3换奇数,然后换偶数,我试着用3换2,用5换4。你知道吗


Tags: andtoforindexsomeconditionslistother
1条回答
网友
1楼 · 发布于 2024-06-02 07:15:16

你在做些奇怪的事。首先,将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将是存储在列表[3]中的任何值,index2将是列表[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]

相关问题 更多 >