未(直接)引用时追加的Python列表

2024-10-01 00:23:00 发布

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

好的,这只是一个粗略的代码,当我试图猜测谁(TM)的类挑战,我想做一个随机字符发生器函数(它只是一个概念证明,我会扩展它的复杂性以后!请不要妄下判断!)。然而,角色的模板特性列表似乎在每次迭代中都会被追加(这样就扭曲了我的其他循环),而实际上它并没有这样做。它应该在每个新生成的列表的末尾添加一个项,而不是模板。但是模板变量并没有附加到代码中,只有一个临时副本是/应该是。代码如下:

tempfeatures = characters = []
for i in range(len(characternames)):
    tempfeatures = []
    charactername = characternames[random.randint(0,len(characternames)-1)]
    characternames.remove(charactername)
    a = features
    tempfeatures = a
    ### "Debug bit" ###
    print(features)
    print("loooooop")
    for y in range(len(features)):
        print(len(features))
        temp = random.randint(0,1)
        if temp == 1:
            tempfeatures[y][1] = True
        else:
            tempfeatures[y][1] = False
    tempfeatures.append(["Dead",True])
    characters.append([charactername,tempfeatures])
print(characters)

谢谢你!你知道吗


Tags: 代码in模板列表forlenrangerandom
2条回答

这称为浅拷贝,它只是将列表引用到另一个变量,如下所示: https://docs.python.org/2/library/copy.html
你需要制作一个独立的拷贝,或者一个深度的拷贝,比如:tempfeature = list(feature),这样更改tempfeature就不会影响feature

显然tempfeature变量是“按引用调用”,而不是“按值调用”。-谢谢你,Python。你知道吗

因此,在复制列表时,必须在变量名的末尾使用这个

tempfeature = feature[:]

(位)

谢谢大家的评论!你知道吗

相关问题 更多 >