在For Loop,Python中动态创建变量 [英] Dynamically Create Variables in For Loop, Python

查看:55
本文介绍了在For Loop,Python中动态创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基于计数在for循环中动态创建变量.

I am trying to dynamically create variables in a for loop based on a count.

我正在使用openpyxl模块遍历工作表.

I'm using the openpyxl module to iterate over a worksheet.

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循环中的变量数量取决于每个工作表中有多少活动列,这些活动列在工作表之间变化.它将吐出错误:

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

我看到了一些使用exec的帖子,但是我对它没有任何经验,而且我似乎总是在阅读有关它如何使您陷入困境的信息.

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.

推荐答案

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

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 Loop,Python中动态创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆