for ws.rows [1:]中的行:TypeError:'generator'对象不可下标

时间:2019-07-25 14:13:26

标签: python excel openpyxl python-3.7

下面的代码使用std::string characterName; std::cout << "Enter your name: "; std::getline(std::cin, characterName); 出错,我不确定为什么:

openpyxl

以下是输出错误:

                Zip = zip_code.group(0)[:6]

                title_column_name = "Member Address Line 3"
                ws = config.workbook.active
                for row in ws.rows[1:]: # errors out here
                    if row[1].value.find(Zip) != -1:
                        print("Found a matching row! MovieId={0}, Title={1}".format(row[0].value, row[1].value))

我只是想获取成功收集的 for row in ws.rows[1:]: TypeError: 'generator' object is not subscriptable 值,并获取找到它的行。 然后,我最终希望获得一个列值

2 个答案:

答案 0 :(得分:1)

您的 ws.rows 是一个不可下标的生成器。

要对其进行切片,可以采取几种方法。

itertools.islice是一个不错的选择。

import itertools
...
<your setup code>
....
    for row in itertools.islice(ws.rows, 1, None):
        ....
        "Now you have skipped the first item"

如果索引为0,则其他选项可能使用enumerate continue ,或者使用next跳过第一个,然后进入循环。

答案 1 :(得分:0)

错误非常简单:wc.rows不是列表(或支持__getitem__的东西),而是生成器。所以问题是,如何跳过第一个元素?请改用itertools.islice

from itertools import islice

...

for row in islice(ws.rows, 1, None):

['a', 'b', 'c', 'd'][slice(1,None)]比较,它等效于['a', 'b', 'c', 'd'][1:]