python - 为什么我的返回列表的类不会迭代?

标签 python class python-2.7 iterator

这是我的代码,我用它打开一个 Excel 工作表,然后将每一行作为字符串列表返回(其中每个单元格都是一个字符串)。该类返回一个列表,该列表包含与文件中的行一样多的列表。所以 50 行将返回 50 个列表。

from xlrd import open_workbook

class ExcelReadLines(object):

    def __init__(self,path_to_file):
        '''Accepts the Excel File'''
        self.path_to_file = path_to_file
        self.__work__()


    def __work__(self):
        self.full_file_as_read_lines = []
        self.book = open_workbook(self.path_to_file)
        self.sheet = self.book.sheet_by_index(0)

        for row_index in range(self.sheet.nrows):
            single_read_lines = []
            for col_index in range(self.sheet.ncols):
                cell_value_as_string = str(self.sheet.cell(row_index,col_index).value)
                cell_value_stripped = cell_value_as_string.strip('u')
                single_read_lines.append(cell_value_stripped)
            self.full_file_as_read_lines.append(single_read_lines)

        return self.full_file_as_read_lines

但是当我运行时:

for x in ExcelReader('excel_sheet'): print x

我收到错误信息:

class is not iterable

最佳答案

为了使类可迭代,它需要有一个__iter__ 方法。

考虑:

class Foo(object):
    def __init__(self,lst):
        self.lst = lst
    def __iter__(self):
        return iter(self.lst)

例子:

>>> class Foo(object):
...     def __init__(self,lst):
...         self.lst = lst
...     def __iter__(self):
...         return iter(self.lst)
... 
>>> Foo([1,2,3])
<__main__.Foo object at 0xe9890>
>>> for x in Foo([1,2,3]): print x
... 
1
2
3

你的例子似乎作为一个生成器会好一点——我真的不明白这里需要一个类是什么:

def excel_reader(path_to_file):
    book = open_workbook(path_to_file)
    sheet = book.sheet_by_index(0)

    for row_index in range(sheet.nrows):
        single_read_lines = []
        for col_index in range(sheet.ncols):
            cell_value_as_string = str(self.sheet.cell(row_index,col_index).value)
            cell_value_stripped = cell_value_as_string.strip('u')
            single_read_lines.append(cell_value_stripped)
        yield single_read_lines

关于python - 为什么我的返回列表的类不会迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14346447/

相关文章:

python - 我需要做什么才能让 Fanjango 工作?

python - 类型错误 : decorated slot has no signal compatible with doubleClicked(QModelIndex)

java - Java 中的静态类有什么用?

javascript - 按类获取元素,以类名定位页面上的所有元素

python - 如何在 python pandas 中使用两个列值创建 url 列数据框?

python - 如何在 wordpress 博客中编写 python 代码?

python - Python + OpenCV + Base64:将框架转换为base64的问题

python - 调试期间的私有(private)变量

python - 安装numpy,仍然有问题

Python:运行 SimpleHTTPServer 并在脚本中向它发出请求