我希望每个键都继承此列表的前一个键。例如,对于每个方法调用,第一个键应该是 1,下一个键应该是 2,然后是 3...n。我的代码有效:
all_randomly_generated_intigers = {}
def new_ID():
y = random.randint(0,5)
x = 0
while x in all_randomly_generated_integers:
x+=1
all_randomly_generated_integers[x] = y
但是,每次调用 new_ID() 时,循环都会运行 x 次。我想我可以只调用 x global 但如果我这样做的话我的方法看不到 x:
all_randomly_generated_intigers = {}
global x
def new_ID():
y = random.randint(0,5)
while x in all_randomly_generated_integers:
x+=1
all_randomly_generated_integers[x] = y
为什么这行不通?
最佳答案
全局x需要在函数内部声明。
关于python - 正在寻找一种更好的方法来为字典、全局整数生成键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51330198/