简体   繁体   English

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

[英]Why won't my class that returns a list iterate?

Here is my code, I use it to open an excel sheet and then return each row as a list of strings (where each cell is a string). 这是我的代码,我用它打开一个excel工作表,然后将每一行作为字符串列表返回(其中每个单元格是一个字符串)。 The class returns one list that is filled with as many lists as there are rows in the file. 该类返回一个列表,该列表填充的列表与文件中的行数一样多。 So 50 rows will return 50 lists. 因此,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

But when I run: 但是当我跑步时:

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

I get the error message: 我收到错误消息:

class is not iterable

In order for a class to be iterable, it needs to have an __iter__ method. 为了使一个类可迭代,它需要一个__iter__方法。

Consider: 考虑:

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

example: 例:

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

Your example seems like it would be a good bit better as a generator -- I don't really understand what the need is for a class here: 您的示例似乎将它作为生成器会更好一些-我真的不明白这里需要什么类:

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

You should look into implementing Python's special iterator methods . 您应该研究实现Python的特殊迭代器方法

Also, note that you shouldn't name a method __work__ since it uses magic method syntax but isn't actually a real magic method. 另外,请注意,您不应命名方法__work__因为它使用魔术方法语法,但实际上并不是真正的魔术方法。

You have a few problems here. 您在这里遇到一些问题。

  1. Your code doesn't return anything. 您的代码不返回任何内容。 You call __work__ but don't return the value. 您调用__work__但不返回该值。

  2. Even if it did, that wouldn't help, because returning something from __init__ doesn't make the object be that thing. 即使这样做,也无济于事,因为从__init__返回内容并不能使对象成为那样。

  3. You don't want your object to be a list anyway, you just want to iterate over it. 无论如何,您都不希望您的对象成为列表,而只想对其进行迭代。

See this question for a simple example of how to write an iterator in Python. 有关如何在Python中编写迭代器的简单示例,请参见此问题

In addition, you shouldn't use double-underscore-sandwich names like __work__ in your code. 另外,您不应在代码中使用双下划线三明治名称,如__work__ That sort of name is by convention reserved for Python-internal use. 按照惯例,此类名称保留给Python内部使用。

Unless I'm mistaken, what you're really after is 除非我弄错了,否则你真正想要的是

def first_sheet(fname):
    wb = xlrd.open_workbook(fname)
    ws = wb.sheet_by_index(0)
    for i in xrange(ws.nrows):
        yield ws.row_values(i) # maybe strip 'u''s - but that looks a bit sus... (probably something to do with your `str`)

list_of_rows = list(first_sheet('somefile.xls'))

Then do any transposition using zip if needs be... 然后在需要时使用zip进行任何转置...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM