【问题标题】:Type Error: Class object not iterable [duplicate]类型错误:类对象不可迭代[重复]
【发布时间】:2017-03-05 12:42:27
【问题描述】:

这可能是个愚蠢的问题,但我刚开始在 Python 中学习 OOP,我正在努力学习这个:

以下代码可以正常工作:

class Name(object):
    def __init__(self):
        self.name=None

C1='Stephen Curry'
C2='Kevin Durant'
C3='LeBron James'
C4='Chris Paul'


nameList=[C1,C2,C3,C4]
nameList.sort()
for e in nameList:
    print (e)

但是,当我在 for 循环中使用 nameList.sort() 时,它给了我“TypeError: 'NoneType' object is not iterable”

class Name(object):
    def __init__(self):
        self.name=None

C1='Stephen Curry'
C2='Kevin Durant'
C3='LeBron James'
C4='Chris Paul'

nameList=[C1,C2,C3,C4]

for e in nameList.sort():
    print (e)

谢谢

【问题讨论】:

    标签: python list class oop iterable


    【解决方案1】:

    sort 返回None,因为它就地对列表进行了排序。如果你想在一个语句中迭代一个排序列表,你应该使用sorted

    for e in sorted(nameList):
        pass
    

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 1970-01-01
      • 2021-03-02
      • 2020-04-18
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      相关资源
      最近更新 更多