【问题标题】:Why string returned from a class instance keeps NoneType type even though IDLE says it is a string?为什么从类实例返回的字符串保持 NoneType 类型,即使 IDLE 说它是一个字符串?
【发布时间】:2013-05-28 11:00:32
【问题描述】:

我正在使用一个返回字符串的类实例。

我调用了这个实例两次并将返回值收集到一个列表中。然后我尝试使用 .sort() 对这两个字符串进行排序。但是,当我这样做时,它会抛出一个错误,指出类型是(Nonetype - 将其视为对象)。

我确实检查了类型(列表的元素),它返回类型“字符串”。我不知道发生了什么事。基本上在空闲时它说我在一个列表中有字符串.. 但是在运行时它会抛出一个错误,说 NoneType(这些字符串的列表)是不可迭代的。

这是一个例子:

list_of_strings = [class_method(args), class_method(another_args)] ## this instance returns string

print type(list_of_strings[0])  #prints type 'str'

错误:

list_sorted = list(list_of_strings.sort())
TypeError: 'NoneType' object is not iterable

非常感谢!

乔治

【问题讨论】:

    标签: python string instance nonetype


    【解决方案1】:

    来自pythondocumentation

    7. sort()reverse() 方法修改列表以节省成本 排序或反转大列表时的空间。提醒你 它们通过副作用操作,它们不返回排序或反转的 列表。

    使用sorted()

    list_sorted = list(sorted(list_of_strings))
    

    【讨论】:

      【解决方案2】:

      你应该使用sorted():

      list_sorted = list(sorted(list_of_strings))
      

      您现在在None 上调用list(),这是.sort() 调用的结果。

      【讨论】:

        猜你喜欢
        • 2020-09-05
        • 1970-01-01
        • 2020-05-03
        • 2018-03-02
        • 2018-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-16
        相关资源
        最近更新 更多