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中使用指针和(de)引用呢?假设你是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