在For循环中动态创建变量,Python

时间:2013-10-04 22:24:41

标签: python excel openpyxl dynamic-variables

我正在尝试根据计数在for循环中动态创建变量。

我正在使用openpyxl模块迭代工作表。

value = ~sheet name after using a loop to iterate over sheet names~
wb = (path_to_workbook, use_iterators = True)
ws = wb.get_sheet_by_name(name = value)

for a,b,c,d in ws.iter_rows():
    print a.internal_value

问题是,for循环中的变量数量取决于每个工作表中有多少活动列从一个工作表更改为工作表。它会吐出错误:

  

“要解压的值太多”

如果我没有正确数量的变量要解压缩到。

我可以使用以下方法获取列数:

ws.get_highest_column()

所以,不知怎的,我需要做一个:

for ~dynamically create variables by count of columns~ in ws.iter_rows():
    print variable1.internal_value

我看到一些使用exec的帖子,但我没有任何经验,我似乎总是读到它如何让你陷入麻烦。

2 个答案:

答案 0 :(得分:5)

无需创建动态数量的参数。请改用一个;它被分配了整行,然后您可以使用索引来访问项目:

for row in ws.iter_rows():
    # row is now a tuple
    first_value = row[0]

答案 1 :(得分:1)

for ~dynamically create variables by count of columns~ in ws.iter_rows():
    print variable1.internal_value

您可以简单地遍历所有行而无需解压缩每个行。

for row in ws.iter_rows():
    # row is a tuple
    print row[0].internal_value
相关问题