"for" 语句中的 list[i] 没有 return 正确的值

list[i] in "for" statement does not return the right values

我有一个for语句,循环变量i,自然每次加1。但是,当我 运行 for 语句中有一行获取某个列表的索引 i 时,它做了一些奇怪的事情。结果是,它 returns 很少有正确的值,而其他值似乎是随机的。

def allchords(thescale,issev):
    for i in range(len(thescale)):
        makechord((thescale[i]),thescale,issev)

i=0 时,returns thescale[0] 正确。

i=1 时,returns thescale[1] 正确。

i=2 时,由于某种原因 returns thescale[3]

i=3时,它returnsthescale[6]

i=4时,它returnsthescale[3]

i=5时,它returnsthescale[1]

i=6时,returnsthescale[0]

这到底是怎么回事?

好的,这是整个 makechord 函数:

def makechord(tnc,thescale,issev):
    crdscl=thescale
    for i in range(len(thescale)):
        if crdscl[0] == tnc:
            break
        else:
            tomove=crdscl[0]
            crdscl.pop(0)
            crdscl.append(tomove)

if issev == "y" or "Y":
    thecrd=[(crdscl[0]),(crdscl[2]),(crdscl[4]),(crdscl[6])]
else:
    thecrd=[(crdscl[0]),(crdscl[2]),(crdscl[4])]
print thecrd

您确实在 makechord() 内修改 thescale:

crdscl=thescale

只是将名字crdscl分配给thescale,所以当你稍后调用

crdscl.pop(0)
crdscl.append(tomove)

你实际上是在修改thescale的内容。避免这种情况的一种简单方法是将内容 thescale 的副本分配给 crdscl:

crdscl = thescale[:]