2 回答

TA贡献1770条经验 获得超3个赞
尝试使用这个函数,你可以有一个函数,所以每次运行时,change变量都会不同:
change = iter(range(100, 200, 5)) # just an example
def next_dict():
changing_dict = {
"key1": next(change),
"key2": next(change),
"key3": next(change),
"key4": 10010
}
return changing_dict
print(next_dict())
print(next_dict())
输出:
{'key1': 100, 'key2': 105, 'key3': 110, 'key4': 10010}
{'key1': 115, 'key2': 120, 'key3': 125, 'key4': 10010}

TA贡献1884条经验 获得超4个赞
您可以定义一个类而不是这样的字典:
change = iter(range(5))
class c:
def get_key1():
return next(change)
c.get_key1() # Output: 0
c.get_key1() # Output: 1
像某些评论一样,我建议您提供更多上下文,因为可能会有更多“Pythonic”来解决您的用例。
添加回答
举报