gpt4 book ai didi

python - 从带有变量的字典中请求一个值

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:29 24 4
gpt4 key购买 nike

我试图在 python 中制作一个串行生成器,当我生成一个数字时,它被分配给一个变量。现在序列有数字和字母。我正在使用变量来存储每个角色,最后我会将它们组合成一个连续剧。所以,到目前为止,我得到了所有的数字,所以我为字母点设置了一个更高的范围。我想使用我已经拥有的变量从字典中调用数字,并将数字归因于它。

我已经尝试过只打印带有变量的字典变量,但它引发了一个错误。

我使用下面的代码:

# ironkeys serial gen prototype 1.0 - python 3.7 | 6 character (alternate 
# characters)
import random

v1 = 0
v2 = 0
v3 = 0
v4 = 0
v5 = 0
v6 = 0

d = {10: "A",11: "B",12: "C",13: "D",14: "E",15: "F",16: "G",17: "H",18:
"I",19: "J",20: "K",21: "L",22: "M",22: "N",23: "O",24: "P",24: "Q",25:
"R",26: "S",27: "T",28: "U",29: "V",30: "W",31: "X",32: "Y",32: "Z"}

def gen():
v1 = random.randint(0,9)
v2 = random.randint(10,33)
v3 = random.randint(0,9)
v4 = random.randint(10,33)
v5 = random.randint(0,9)
v6 = random.randint(10,33)

def letterAssignAndPrint(v2, v4, v6):
checkVar1 = d[v2]
checkVar2 = d[v4]
checkVar3 = d[v6]
print(v1, checkVar1, v3, checkVar2, v5, checkVar3)

当我尝试运行上面的代码时出现以下错误:

Traceback (most recent call last)
<ipython-input-24-d45f5b5c2e55> in <module>
----> 1 print(d[v2])

KeyError: 0

最佳答案

为什么不只是这样:

from random import choice
from string import ascii_uppercase, digits

serial = "".join((choice(digits) + choice(ascii_uppercase) for _ in range(3)))
print(serial)

string.digits = "0123456789"(参见 string constants ); random.choice 选择其中之一。剩下的只是组装一个数字的 3 倍,然后是一个字母。


在您的示例中,v2 似乎是 0,并且在您的字典 d 中没有对应的键。

关于python - 从带有变量的字典中请求一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57547515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com