【问题标题】:Returning list results in none返回列表结果为无
【发布时间】:2016-08-23 16:46:09
【问题描述】:

所以我正在开发一个小程序,通过 GUI 从给定文件中删除重复项,以学习如何使用 Python 制作 GUI。

我编写了一个方法,它应该采用string,将其转换为list,从list 中删除重复项,它实际上就是这样做的。 当我想return 结果时会出现问题,因为如果我print() 返回值,它只会导致None 被打印。但是,如果我在方法中print() 我想要return 的值,它会打印出正确的列表。

这个类看起来像这样:

#Class that removes the duplicates
class list_cleaner():
    def __init__(self):
        self.result_list = []

    def clean(self,input_string, seperator, target):
        #takes a string and a seperator, and splits the string at the seperator. 
        working_list = self.make_list_from_string(input_string,seperator)

        #identify duplicates, put them in the duplicate_list and remove them from working_list 
        duplicate_list = []
        for entry in working_list:
            instances = 0
            for x in working_list:
                if entry == x:
                    instances =  instances + 1
            if instances > 1:
                #save the found duplicate
                duplicate_list.append(entry)
                #remove the duplicate from working list
                working_list = list(filter((entry).__ne__, working_list))

        self.result_list = working_list + duplicate_list 
        print(self.result_list) #Prints the result list
        return self.result_list

主函数如下所示(注意:duplicate_remover 是 list_cleaner 的门面):

if __name__ == "__main__":
    remover = duplicate_remover()
    x = remover.remove_duplicates("ABC,ABC,ABC,DBA;DBA;DBA,ahahahaha", ",")
    print(x) #Prints none. 

TL;DR:

我有一个方法f,它返回listl,它是C 类的一个属性。

如果 i print() l 作为 f 的一部分,则正在打印 l 的值。

如果我返回l 并将其存储在f 范围之外的变量中,然后print() 这个变量将打印None

提前致谢!

编辑 1:

请求了duplicate_remover 代码。 看起来是这样的:

class duplicate_remover():
    def remove_duplicates(self,input_string,seperator):
        my_list_cleaner = list_cleaner()
        my_list_cleaner.clean( input_string = input_string, seperator = seperator)

【问题讨论】:

  • 看起来duplicate_remover 是罪魁祸首。
  • 我现在将发布duplicate_remover :) (尝试将其添加到此评论但格式化)
  • 请将其编辑到您的问题中。

标签: python list return nonetype


【解决方案1】:

remove_duplicates忘记返回my_list_cleaner.clean(...)的返回值,导致返回默认值None

【讨论】:

  • 我不敢相信这是答案...非常感谢!我现在就去给自己挖个坑……
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 2022-07-29
  • 1970-01-01
  • 2022-08-04
  • 2016-01-03
  • 1970-01-01
相关资源
最近更新 更多