2 回答

TA貢獻1770條經(jīng)驗 獲得超3個贊
嘗試使用這個函數(shù),你可以有一個函數(shù),所以每次運行時,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條經(jīng)驗 獲得超4個贊
您可以定義一個類而不是這樣的字典:
change = iter(range(5))
class c:
def get_key1():
return next(change)
c.get_key1() # Output: 0
c.get_key1() # Output: 1
像某些評論一樣,我建議您提供更多上下文,因為可能會有更多“Pythonic”來解決您的用例。
添加回答
舉報