【问题标题】:Why does appending to a python list set its type to None为什么附加到 python 列表将其类型设置为无
【发布时间】:2018-12-22 14:33:10
【问题描述】:

我查看了 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.")

它输出:

Traceback(最近一次调用最后一次):

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

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

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

对于行星排序中的 p:

TypeError: 'NoneType' 对象不可迭代

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

【问题讨论】:

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


    【解决方案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() 方法转换应用它的对象,而不是返回排序列表。

    【讨论】:

      【解决方案2】:

      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”。

      【讨论】:

        【解决方案3】:

        list.sort() 对列表进行就地排序并返回 None,而 list.sorted() 则符合您的预期。

        要么调用sort() 并使用原始的、现已排序的列表:

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

        或者改用sorted()函数:

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

        【讨论】:

          猜你喜欢
          • 2010-11-22
          • 2015-06-03
          • 2021-07-22
          • 2014-01-30
          • 1970-01-01
          • 2018-03-17
          • 2021-03-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多