[英]Python references to references in python
我有一個函數,它使用給定的一組變量初始條件,並將結果放入另一個全局變量。 例如,假設其中兩個變量是x和y。 請注意,x和y必須是全局變量(因為它太凌亂/不便,無法在許多函數之間傳遞大量引用)。
x = 1
y = 2
def myFunction():
global x,y,solution
print(x)
< some code that evaluates using a while loop >
solution = <the result from many iterations of the while loop>
我想看看給定x和y(和其他變量)的初始條件的變化結果如何變化。 為了提高靈活性和可伸縮性,我想執行以下操作:
varSet = {'genericName0':x, 'genericName1':y} # Dict contains all variables that I wish to alter initial conditions for
R = list(range(10))
for r in R:
varSet['genericName0'] = r #This doesn't work the way I want...
myFunction()
這樣,“ myFunction”中的“ print”行會在連續調用中輸出值0、1、2,...,9。
所以基本上我在問您如何將鍵映射到一個值,而該值不是標准數據類型(如int),而是對另一個值的引用? 完成此操作后,您如何引用該值?
如果無法按照我的意願進行操作:通過僅更改(要設置的變量的名稱)來更改任何給定變量的值的最佳方法是什么?
我使用的是Python 3.4,因此希望使用一種適用於Python 3的解決方案。
編輯:修復了較小的語法問題。
EDIT2:我認為提出問題的一種更清晰的方法是:
考慮您有兩個字典,一個包含圓形對象,另一個包含水果。 一本詞典的成員也可以屬於另一本詞典(蘋果既是水果又是圓形的)。 現在考慮兩個字典中都有鍵“ apple”,並且該值指的是蘋果的數量。 在更新一組蘋果的數量時,您希望該數字也轉移到圓形對象字典中,在“蘋果”鍵下,而無需您自己手動更新字典。 處理此問題的最pythonic方法是什么?
不必使用單獨的字典來使x
和y
全局變量引用它們,而是使字典直接包含“ x”和“ y”作為鍵。
varSet = {'x': 1, 'y': 2}
然后,在代碼中,每當要引用這些參數時,請使用varSet['x']
和varSet['y']
。 當您要更新它們時,請使用varSet['x'] = newValue
,依此類推。 這樣,詞典將始終是“最新的”,並且您不需要存儲對任何內容的引用。
我們將以您的第二次編輯中給出的水果為例:
def set_round_val(fruit_dict,round_dict):
fruit_set = set(fruit_dict)
round_set = set(round_dict)
common_set = fruit_set.intersection(round_set) # get common key
for key in common_set:
round_dict[key] = fruit_dict[key] # set modified value in round_dict
return round_dict
fruit_dict = {'apple':34,'orange':30,'mango':20}
round_dict = {'bamboo':10,'apple':34,'orange':20} # values can even be same as fruit_dict
for r in range(1,10):
fruit_set['apple'] = r
round_dict = set_round_val(fruit_dict,round_dict)
print round_dict
希望這可以幫助。
從我從@BrenBarn和@ebarr的響應中收集到的信息來看,這是解決此問題的最佳方法(並直接回答EDIT2)。
創建一個封裝公共變量的類:
class Count:
__init__(self,value):
self.value = value
創建該類的實例:
import Count
no_of_apples = Count.Count(1)
no_of_tennis_balls = Count.Count(5)
no_of_bananas = Count.Count(7)
創建兩個都具有公共變量的字典:
round = {'tennis_ball':no_of_tennis_balls,'apple':no_of_apples}
fruit = {'banana':no_of_bananas,'apple':no_of_apples}
print(round['apple'].value) #prints 1
fruit['apple'].value = 2
print(round['apple'].value) #prints 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.