按列表中的值递增第 i 列元素

Increment column i element by values inside list

我有一个循环,它在文本文件中搜索关键字并将关键字后面的整数粘贴到 excel 文件中。我希望整数位于 excel 文件中的特定单元格中。是否可以将 i 增加 i_list 中的值而不是像示例中那样总是增加 5?

i_list = [5,3,1,1]

def search(file, excel_file):
    i = 2
    found_keywords = list()
    wb = load_workbook(excel_file)
    sheets = wb.sheetnames
    sheet1 = wb[sheets[0]]

    for kwrd in keywords:
        for line in file:
            if kwrd in line and kwrd not in found_keywords:
                found_keywords.append(kwrd)
                sheet1.cell(row=3, column=i).value = int(re.search(r"\d+", line).group())
                i += 5
            elif kwrd in line:
                continue

    wb.save(excel_file)

此代码片段根据原始内容进行了调整,循环遍历 i_list 的值:

i_list = [5,3,1,1]

def search(file, excel_file):
    i = 2
    found_keywords = list()
    wb = load_workbook(excel_file)
    sheets = wb.sheetnames
    sheet1 = wb[sheets[0]]

    for kwrd in keywords:
        for line in file:
            if kwrd in line and kwrd not in found_keywords:
                for i in i_list: # Update i based on the i-list value
                    sheet1.cell(row=3, column=i).value = int(re.search(r"\d+", line).group())
            elif kwrd in line:
                continue
    wb.save(excel_file)

如果您不需要循环遍历 i 的值,那么您可以创建一个生成器来 return 将 i 的值一个一个地生成。我已经将 i 的下一个值的调用包装在一个 try 块中,因为一旦您 运行 超出了值,代码就不知道该怎么做。所以我们打破循环

i_list = (i for i in [5,3,1,1])
i = 2
for _ in range(10):
    print(i)
    try:
        i += next(i_list)
    except StopIteration as si:
        print("no more values in i so loop terminating")
        break

输出

2
7
10
11
12
no more values in i so loop terminating

但是,如果您想循环遍历 i 的值,您可以使用 itertools 模块中的循环,并根据需要无限地从 i_list 中获取下一项

from itertools import cycle
i_list = cycle([5,3,1,1])
i = 2
for _ in range(10):
    print(i)
    i += next(i_list)

输出

2
7
10
11
12
17
20
21
22
27

您的代码更新

下面是根据您所说的不必循环这一事实对您的代码进行的更新。请记住,一旦到达 i_list 的末尾,您的代码将无法增加 i,因为 i_list.

中没有更多值
i_list = [5,3,1,1]
i_generator = (i for i in i_list)

def search(file, excel_file):
    i = 2
    found_keywords = list()
    wb = load_workbook(excel_file)
    sheets = wb.sheetnames
    sheet1 = wb[sheets[0]]

    for kwrd in keywords:
        for line in file:
            if kwrd in line and kwrd not in found_keywords:
                found_keywords.append(kwrd)
                sheet1.cell(row=3, column=i).value = int(re.search(r"\d+", line).group())
                i += next(i_generator)
            elif kwrd in line:
                continue

    wb.save(excel_file)