为啥我的程序在 for 循环中返回 None?

Posted

技术标签:

【中文标题】为啥我的程序在 for 循环中返回 None?【英文标题】:why does my program return None in for loop?为什么我的程序在 for 循环中返回 None? 【发布时间】:2016-09-21 01:15:20 【问题描述】:

我有一个函数可以打印给定间隔内的正方形:

class Squares:

    def __init__(self, min, max):
        self.min = min
        self.max = max

    def __iter__(self):
        return self

    def __next__(self):
        a_list = []
        for i in range((self.max)+1):
            a_list += [i**2]

        if self.min <= self.max:
            if self.min in a_list:
                result = self.min
                self.min += 1
                return result
            else:
                self.min += 1

        else:
            raise StopIteration

import math

for i in Squares(5, 50):

    print(i) 

它应该打印 9、16、25、49,但输出是:

None
None
None
None
9
None
None
None
None
None
None
16
None
None
None
None
None
None
None
None
25
None
None
None
None
None
None
None
None
None
None
36
None
None
None
None
None
None
None
None
None
None
None
None
49
None

这是为什么?

【问题讨论】:

您没有从内部 else: 块返回任何内容? 如果号码不在列表中,那么不需要返回,对吗? 迭代器必须返回下一个值。如果没有,那么您将获得当前所看到的内容。因此,要么将您的代码更改为 a) 生成一个仅包含正方形的列表,要么 b) 跳过不是正方形的值。 【参考方案1】:

每次变量result不是正方都返回None的原因是next()函数如果不指定return默认返回None .

如果您必须为此项目使用迭代器,则必须构造代码以便每次传递都返回一个值。

另外,请注意,每次调用 next() 时,都会生成一个名为 a_list 的全新数组,这非常低效。初始化该数组一次会更好。

查看此示例中的差异。

class Squares:

def __init__(self, min, max):
    self.min = min
    self.max = max

def __iter__(self):
    self.a_list = []
    for i in range((self.max)+1):
        self.a_list += [i**2]
    self.iter_index = 0
    return self

def next(self):
    self.iter_index += 1
    if self.a_list[self.iter_index] > self.max:
        raise StopIteration
    else:
        return self.a_list[self.iter_index]

import math
import pdb

for i in Squares(5, 50):
    print(i) 

【讨论】:

以上是关于为啥我的程序在 for 循环中返回 None?的主要内容,如果未能解决你的问题,请参考以下文章