我的字典有以下结构:
a = 'stringA'
b = 'stringB'
c = 'stringC'
endpoints = {
'foo1': a + 'string1' + b,
'foo2' : a + 'string2' + c + 'string3' + b,
}我的问题是:当我调用endpoints['foo2']时,我得到了预期的数组值。但是,当我在数组声明和endpoints['foo2']的使用之间更改例如endpoints['foo2']的值时,c的值不会被更新。
你知不知道为什么会发生这种情况,如何解决?
PS:我知道这可以创建一个简单的函数,但我认为这样做效率会更低。
发布于 2016-03-28 09:56:36
你可以这样做:
a = ['stringA']
b = ['stringB']
c = ['stringC']
endpoints = {
'foo1': a ,
'foo2' : b
}
print(endpoints['foo1']) #returns "[stringA]"
a[0]='otherString'
print(endpoints['foo1']) #returns "[otherString]"您可以这样做,因为您可以更改列表中的值而不更改引用;
a和endpoints仍在为a使用相同的空间
对于纯字符串来说,这是不可能的,因为如果没有新的赋值,就不能更改它们。Python中的字符串是不可变的。
编辑:另一种可能是创建自己的字符串类。
这消除了[]括号:
class MyStr:
def __init__(self,val):
self.val=val
def __repr__(self):
#this function is called by dict to get a string for the class
return self.val
def setVal(self,val):
self.val=val
a=MyStr("abcd")
b={1:a}
print(b) #prints {1:"abcd"}
a.setVal("cdef")
print(b) #prints {1:"cdef"}免责声明:正如注释中所解释的,我仍然使用python2.7
虽然Python 3和2.7基本上是兼容的,但在尝试使用它时可能会出现一些较小的bug。
https://stackoverflow.com/questions/36259740
复制相似问题