关于在不使用全局或重新分配的情况下更改值的Python

时间:2016-11-24 22:08:18

标签: python python-2.7 python-3.x

我正在努力解决python问题。在下面的代码中,我必须将str1和str2重新分配给函数零内部传递的值...我们被要求不设置全局变量而不使用str1,str2 = 0(s1,s2)有点没有&# 39;对我来说,为什么我们不应该这样做。

请善待我帮我解决这个问题!谢谢!

这是我到目前为止所得到的......

def zero(s1,s2):

      #Initial values passed into the function
      print("Start of ZERO s1 is :" , s1)
      print("Start of ZERO s2 is :" , s2)

      #setting new values for s1 and s2
      s1 = [1,2,3]
      s2 = [4,5,6]

      #printing changes new values of s1 and s2
      print("\nEnd of ZERO s1 is ", s1)
      print("\nEnd of ZERO s2 is ", s2)

      return s1,s2

str1 = 'spam'
str2 = {1:'m' , 'p' : 'a'}

#values of str1 and str2 which should be changed to s1 and s2 inside the function should be here......

1 个答案:

答案 0 :(得分:0)

我能想到这样做的一种方法是将str1和str2放入dict并将函数改为dict,这有点偷偷摸摸。

除非你深刻复制一个dict,否则你仍然会引用同一个对象,所以当你改变它时你会改变底层对象。

我会修改你的代码如下:

def zero(str_dict):

    s1 = str_dict['str1']
    s2 = str_dict['str2']

    #Initial values passed into the function
    print("Start of ZERO s1 is :" , s1)
    print("Start of ZERO s2 is :" , s2)

    #setting new values for s1 and s2
    s1 = [1,2,3]
    s2 = [4,5,6]

    #printing changes new values of s1 and s2
    print("\nEnd of ZERO s1 is ", s1)
    print("\nEnd of ZERO s2 is ", s2)

    str_dict['str1'] = s1
    str_dict['str2'] = s2

str1 = 'spam'
str2 = {1:'m' , 'p' : 'a'}

#values of str1 and str2 which should be changed to s1 and s2 inside the function should be here......

现在测试:

str_dict = {
    "str1": str1,
    "str2": str2
}

print str_dict

zero(str_dict)

print str_dict

我看到以下输出:

{'str2': {1: 'm', 'p': 'a'}, 'str1': 'spam'}
('Start of ZERO s1 is :', 'spam')
('Start of ZERO s2 is :', {1: 'm', 'p': 'a'})
('\nEnd of ZERO s1 is ', [1, 2, 3])
('\nEnd of ZERO s2 is ', [4, 5, 6])
{'str2': [4, 5, 6], 'str1': [1, 2, 3]}