python - 正在寻找一种更好的方法来为字典、全局整数生成键?

标签 python python-3.x

我希望每个键都继承此列表的前一个键。例如,对于每个方法调用,第一个键应该是 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/

相关文章:

Python - 在 "detached"进程中生成函数的最佳方式

python - 安装不带 gcc 的 psutil

python - MySQL服务器消失了

python - 正则表达式返回前缀为 "="的值

python - 如何将网站上的图片保存到本地文件夹

python - 在 python 中加载包内模块

python - 将字符串拆分为 2 个字母的段

python-3.x - 如何从 gensim 上的 w2v 获取 tf-id

python 周期性循环成语?

python - 如何更改列表中项目的类型?