我可以在 Python 3 中访问循环中变量的内存位置和值(指针和引用)吗
Can I access memory location and values ( pointers and reference ) for variables in a loop, in Python 3
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 中使用指针和(取消)引用?
假设您是 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
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 中使用指针和(取消)引用?
假设您是 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