“for”语句中的list[i]没有返回正确的值

2024-09-30 01:33:07 发布

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

我有一个带有循环变量ifor语句,每次自然增加1。但是,当我运行for语句时,有一行获取某个列表的索引i,它会做一些奇怪的事情。所发生的是,它返回的正确值很少,其他值似乎是随机的。你知道吗

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

i=0时,它会正确返回thescale[0]。你知道吗

i=1时,它会正确返回thescale[1]。你知道吗

i=2时,它出于某种原因返回thescale[3]。你知道吗

i=3时,它返回thescale[6]

i=4时,它返回thescale[3]

i=5时,它返回thescale[1]

i=6时,它返回thescale[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

Tags: inforlenifdefrange语句else
1条回答
网友
1楼 · 发布于 2024-09-30 01:33:07

您确实在thescale内修改makechord()

crdscl=thescale

只需将名称crdscl分配给thescale,以便以后调用

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

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

crdscl = thescale[:]

相关问题 更多 >

    热门问题