我的 python 代码是关于从 dict 键生成序列号,并且我的 dict 键是使用模块中的cycle包定义的范围。itertools
working example:
from itertools import cycle
e = {'Apple': cycle(range(1,999)),'Orange': cycle(range(1,999)),'Banana': cycle(range(1,999))}
def SequenceNum(f):
return f'{next(e[f])}'.zfill(3)
X = SequenceNum('Apple')
print(X)
output
001 --> it keeps incrementing in the range specified above in dict `e`
Challenge:
我的要求是将此字典e转换为 json 文件。因此它将通过解析 json 文件来加载键和值。
cat test.json
{
"DATA": {
"Apple": "cycle(range(1,999))",
"Orange": "cycle(range(1,999))",
"Banana": "cycle(range(1,999))"
}
}
(我必须将 dict 值放在双引号内以避免 json 文件加载错误。)
code
import json
from itertools import cycle
with open('test.json') as f:
FromJson = json.load(f)
d = FromJson['DATA']
print(d)
def SequenceNum(f):
return f'{next(d[f])}'.zfill(3)
X = SequenceNum('Apple')
i = 1
while i <= 10:
print(i, SequenceNum('Apple'))
i += 1
这里新的 dict 是d加载 json 文件,它将加载单引号中的值。
output
{'Apple': 'cycle(range(1,999))', 'Orange': 'cycle(range(1,999))', 'Banana': 'cycle(range(1,999))'} #THIS IS OUTPUT of 'd' after loading json file
Traceback (most recent call last):
File "c:\Users\chandu\Documents\test.py", line 14, in <module>
print(i, SequenceNum('Apple'))
File "c:\Users\chandu\Documents\test.py", line 12, in SequenceNum
return f'{next(d[f])}'.zfill(3)
TypeError: 'str' object is not an iterator
它给出了错误,因为我的 dict 值不能通过循环 itertools 模块正确迭代,因为它们在引号中。我不知道这个错误是否还有其他原因。
陪伴而非守候
相关分类