Skip to main content
 首页 » 编程设计

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

2025年05月04日10傻小

这是我的代码,我用它打开一个 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