【问题标题】:Loop returns correct changes when outside function, does not show changes when run inside function循环在函数外返回正确的更改,在函数内运行时不显示更改
【发布时间】:2016-11-09 03:44:21
【问题描述】:

我正在迭代字典中的旧键。我已经在函数外部测试了 for 循环并获得了预期的结果,但是当我将它放入函数时,它会返回旧键。

一直在讨论论坛,但一无所获。

edu_dict = {
        "A.S":"Attended Vocational/Technical",
        "AAS":"Attended Vocational/Technical",...etc}

def clean_edu(edu_dict):

    for i in list(edu_dict):

        key = i  # accesing the key from the edu_dic
        lower_case = key.lower() # changing the key to lower case

        char_change = "".maketrans(chars_in, chars_out)        

        clean = lower_case.translate(char_change)      

        y = re.sub(r'\s\s{1,}','',clean)

        edu_dict[y] =  edu_dict.pop(i)      

        return edu_dict

clean_edu(edu_dict)
print(edu_dict)

这似乎是一个简单的解决方案,但我很难过。

【问题讨论】:

标签: function loops for-loop dictionary iteration


【解决方案1】:

您需要传递对字典的引用,否则您将只是在函数中修改它的副本。该函数修改了这个副本,但在函数之外,原始字典将保持不变。

【讨论】:

    【解决方案2】:

    我认为你要么没有将引用传递给 clean_edu,要么没有保存 clean_edu 的返回值。在这两种情况下,您都是在清理字典的副本,而不是按预期更改原始对象。然后打印原始未修改的字典。

    【讨论】:

      猜你喜欢
      • 2015-04-25
      • 2018-08-26
      • 2011-04-10
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 2013-08-17
      • 1970-01-01
      相关资源
      最近更新 更多