繁体   English   中英

Python对python中引用的引用

[英]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方法是什么?

不必使用单独的字典来使xy全局变量引用它们,而是使字典直接包含“ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM