我想创建一个字典,每次使用时都会更新其键
我尝试过的事情:
import itertools
changing_dict = {
"key1": next(change),
"key2": next(change),
"key3": next(change),
"key4": 10010
}
print(changing_dict)
# Output
# {'key1': 100, 'key2': 105, 'key3': 110, 'key4': 10010}
print(changing_dict)
# Output
# {'key1': 100, 'key2': 105, 'key3': 110, 'key4': 10010}
预期产量
print(changing_dict)
# Output
# {'key1': 100, 'key2': 105, 'key3': 110, 'key4': 10010}
print(changing_dict)
# Output
# {'key1': 115, 'key2': 120, 'key3': 125, 'key4': 10010}
有关如何执行此操作的任何帮助,甚至有可能,因为在创建字典时会计算可迭代的值。
实际的问题是在每次使用此字典时都会在其中创建配置文件,并使用新的端口号获取它。
答案 0 :(得分:2)
尝试使用此功能,您可以拥有一个功能,因此每次运行时,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}
答案 1 :(得分:1)
您可以定义一个类,而不是像这样的字典:
change = iter(range(5))
class c:
def get_key1():
return next(change)
c.get_key1() # Output: 0
c.get_key1() # Output: 1
像一些评论一样,我建议您提供更多上下文,因为可能会有更多的“ Pythonic”来解决您的用例。