简体   繁体   English

从列表中删除而不影响虚拟变量

[英]Removing from a list without affecting a dummy variable

 from random import choice

inputs=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
func={}
code=""
z=len(inputs)
x=z-1
temp=inputs
while x>=0:
    y=choice(temp)
    print(str(x)+"   "+inputs[x]+"   "+y)
    func[inputs[x]]=y
    code=code+inputs[x]+y
    del temp[x]
    x=x-1
    print(temp)
    print(inputs)

Why does this code not asign every element of inputs to a unique and random element of inputs(as the temp dummy set)? 为什么此代码没有将输入的每个元素分配给输入的唯一且随机的元素(作为临时虚拟集)? it seems to delete items from both temp and inputs when only told to delete items from the dummy set. 当仅被告知从虚拟集中删除项目时,似乎同时从临时和输入中删除项目。

Thanks for any help. 谢谢你的帮助。

You are creating an alias of your list instead of a true copy of it: replace temp=inputs with temp=inputs[:] 您正在创建列表的别名,而不是列表的真实副本:用temp=inputs[:]替换temp=inputs

import random

inputs =  ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0']
func = {}
code = ""
z = len(inputs)
x = z-1
temp = inputs[:]    #<-- here
while x >= 0:
    y = random.choice(temp)
    print(str(x) + "   " + inputs[x] + "   " + y)
    func[inputs[x]] = y
    code = code+inputs[x] + y
    del temp[x]
    x = x - 1
    print(temp)
    print(inputs)

You are not making a copy of 'inputs' when you do 'temp=inputs', but making a new variable to access the same content. 当您执行'temp = inputs'时,您不是在复制'inputs',而是在创建一个新变量来访问相同的内容。 If you want a new copy of the list, then use 'temp = inputs[:]'. 如果要列表的新副本,请使用'temp = inputs [:]'。 Otherwise you are just creating a new reference to the same object, but not duplicating the object itself. 否则,您将只是创建对同一对象的新引用,而不是复制对象本身。

You can find more about this in the official Python FAQ . 您可以在官方Python FAQ中找到有关此内容的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM