简体   繁体   English

在For Loop,Python中动态创建变量

[英]Dynamically Create Variables in For Loop, Python

I am trying to dynamically create variables in a for loop based on a count. 我正在尝试基于计数在for循环中动态创建变量。

I'm using the openpyxl module to iterate over a worksheet. 我正在使用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

The problem is, that the amount of variables in the for loop, depends on how many active columns there are in each sheet which changes from sheet to sheet. 问题是,for循环中的变量数量取决于每个工作表中有多少活动列,这些活动列随工作表而变化。 It will spit out the error: 它将吐出错误:

"Too many values to unpack" “太多价值无法解包”

if I don't have the correct amount of variables to unpack to. 如果我没有正确数量的变量可解包。

I can get the count of columns by using: 我可以使用以下方法获取列数:

ws.get_highest_column()

So, somehow I need to do a: 因此,我需要以某种方式执行以下操作:

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

I saw some posts using exec, but I don't have any experience with it and I always seem to read about how it can get you into trouble. 我看到一些使用exec的帖子,但是我对它没有任何经验,而且我似乎总是在阅读有关它如何使您陷入困境的信息。

There is no need to create a dynamic number of arguments. 无需创建动态数量的参数。 Use one instead; 改用一个 it is assigned the whole row and you can then use indexes to access items: 它被分配了整行,然后您可以使用索引来访问项目:

for row in ws.iter_rows():
    # row is now a tuple
    first_value = row[0]
for ~dynamically create variables by count of columns~ in ws.iter_rows():
    print variable1.internal_value

You can simply iterate over all the rows without unpacking each one. 您可以简单地遍历所有行而无需解压每一行。

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

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

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