为什么追加到python列表后将其类型设置为None

时间:2018-12-22 14:33:10

标签: python-3.x for-loop iterator append typeerror

我仔细阅读了Stack Exchange的其余部分,发现了与我的问题相似但又不相同且无济于事的问题。

我的代码如下:

class star:
    def __init__(self):
        # irrelevant other variables
        self.planets = []

    def genPlanets(self):
        self.planets.append(random.uniform(self.frostLine*0.98, self.frostLine*1.02))
        print ("There is a planet at " + str(self.planets[0]) + " AU away from the star.")

这部分代码将以下内容输出到控制台:

  

[]

     

有一颗行星位于2.916687900748318 AU,距离恒星较远。

但是,在代码的下一部分中:

def genPlanets:
    # irrelevant, working code.

    planetSort = planets.sort()
    for p in planetSort:
        file.write("There is a planet at " + str(p) + " AU away from the star.")

它输出:

  

回溯(最近通话最近一次):

     

中的文件“ C:\ Users \ Dominic \ Documents \ Coding \ The Galaxy Maker \ MAin.py”,第145行      

Star.outerHabitable,Star.innerPlanetary,Star.outerPlanetary,Star.frostLine,Star.planets)

     

writeData中的文件“ C:\ Users \ Dominic \ Documents \ Coding \ The Galaxy Maker \ MAin.py”,第125行

     

对于PlanetSort中的p:

     

TypeError:“ NoneType”对象不可迭代

我不明白这是怎么发生的,也看不到append函数为什么会返回None类型!请帮忙!

3 个答案:

答案 0 :(得分:1)

尝试一下:

def genPlanets:
    # irrelevant, working code.

    planets.sort()
    for p in planets:
        file.write("There is a planet at " + str(p) + " AU away from the star.")

.sort()方法转换您应用它的对象,而不是返回排序后的列表。

答案 1 :(得分:0)

  

def genPlanets:       #不相关的有效代码。

planetSort = planets.sort()
for p in planetSort:
    file.write("There is a planet at " + str(p) + " AU away from the star."

在这里,planetSort没什么,因为您没有为行星指定值进行排序,因此错误显示为'NoneType'。

答案 2 :(得分:0)

list.sort()对列表进行原位排序并返回None,而list.sorted()则按您的期望进行操作。

调用sort()并使用原始的,已排序的列表:

planets.sort()
for p in planets:
    ...

或改为使用sorted()函数:

planetSort = planets.sorted()
for p in planetSort:
    ...