my_num_1 = 10
my_num_2 = 20
# I want to assign value 5 to above two variables like this:
for num in [my_num_1, my_num_2]:
num = 5
那是行不通的。那么有沒有辦法做這樣的偽代碼:
for num in [(address_of)my_num_1, (address_of)my_num_2]:
(value_at)num = 5
我知道代碼和應用程??序很糟糕。但是有沒有辦法像這樣在 Python 中使用指標和(取消)參考?
uj5u.com熱心網友回復:
假設你是 Python 的初學者
你想要的是一本字典或一個串列。如果您需要變數名,請使用字典,但在這種情況下,串列可能是一個更好的主意。
字典示例實作:
nums={
"my_1": 10,
"my_2": 20,
} #Create a dictionary of your nums
print(nums["my_1"]) #10
print(nums["my_2"]) #20
for num in nums: #Iterate through the keys of the dictionary
nums[num] = 5 #and set the values paired with those keys to 5
print(nums["my_1"]) #5
print(nums["my_2"]) #5
列出示例實作:
nums = [10, 20] #Create a list and populate it with your numbers
print(nums[0]) #10
print(nums[1]) #20
for num in range(len(nums)): #Keys for your list
nums[num] = 5 #Set the values within the list
print(nums[0]) #5
print(nums[1]) #5
假設你是一個中等水平的程式員
你可以改變globals()字典。
my_num_1 = 10
my_num_2 = 20
print(my_num_1) #10
print(my_num_2) #20
for name in ("my_num_1", "my_num_2"): #Iterate through a tuple of your names
globals()[name] = 5 #and mutate the globals dict
print(my_num_1) #5
print(my_num_2) #5
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/486438.html
