【问题标题】:Why does my python function remember a "set" variable? [duplicate]为什么我的 python 函数会记住一个“set”变量? [复制]
【发布时间】:2022-11-17 22:17:39
【问题描述】:

我正在尝试运行一个递归程序,该程序采用一个元素并迭代其中包含的相似元素但从不重复。我想使用集合类型对象跟踪选中的元素,并且我想根据需要多次重复该过程。这是我的代码

def assaignPuntuation(song, assigned={"0"}):
 if( song in assigned ):
  return  assigned 
 assigned.add(song)
 def runthrough(songlist, song, assigned):
  for element in songlist:
   assigned = assaignPuntuation (song,assigned=assigned)
  return assigned
 ...
 assigned = runthrough (song, song[4], assigned)
 ...
 return assigned

assaignPuntuation(A)
assaignPuntuation(B)

B包含在A的歌曲列表中,但在没有指明的情况下不应以A中选中的所有歌曲开头,但确实如此。

我希望每次仅使用歌曲调用该函数时该集合都以 {"0"} 开头,但它第一次保存了该值,所以我不能第二次重复它。我尝试将变量的名称更改为不同的名称,但它一直在发生,我不知道为什么。

【问题讨论】:

    标签: python function


    【解决方案1】:

    创建函数时,函数头会在程序开始时执行一次。 所以在你的情况下

    def assaignPuntuation(song, assigned={"0"}):
    

    为您的默认参数 assigned 创建一个带有初始化集的函数对象。

    这就是为什么 assaignPuntuation 的每个后续调用都会获得初始初始化的 assigned 集,您可以在函数内部对其进行变异。

    为了避免这种意外的突变,在处理可变数据类型时遵循这种方法:

    def assaignPuntuation(song, assigned=None):
        if assigned is None:
            assigned = {"0"}
        # Rest of your function
    

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 2016-01-16
      • 1970-01-01
      • 2019-08-15
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      相关资源
      最近更新 更多