首页 文章

返回列表结果为none

提问于
浏览
3

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

我写了一个方法应该采用 string ,将其转换为 list ,从 list 删除重复项,它实际上是这样做的 . 当我想要 return 结果时会出现问题,因为如果我 print() 返回的值只会导致 None 被打印 . 但是,如果我想要在方法中使用 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

main函数看起来如此(注意: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 返回 list l 这是类 C 的属性 .

如果我 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)

1 回答

  • 3

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

相关问题