2013-08-28 24 views
2

我试图压缩一些先前在python中编写的代码。我有一些在Excel工作簿中循环查找表的代码。大约有20张工作簿中包含查找表。我想遍历每个查找表中的值并将它们添加到他们自己的列表中。我现有的代码如下所示:Dynamicaly在Excel工作簿中从表格构建Python列表

test1TableList = [] 
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"): 
    test1TableList.append(row.Code) 

test2TableList = [] 
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"): 
    test2TableList.append(row.Code) 

test3TableList = [] 
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"): 
    test3TableList.append(row.Code) 

test4TableList = [] 
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"): 
    test4TableList.append(row.Code) 

test5TableList = [] 
for row in arcpy.SearchCursor(r"Z:\Excel\LOOKUP_TABLES.xlsx\LookupTable1$"): 
    test5TableList.append(row.Code) 

内容非常重要

我想压缩代码(也许在一个函数)。

问题需要解决:

  1. 表的名称都不同。我需要遍历Excel工作簿中的每个工作表,以便a)抓取工作表对象和b)使用工作表名称作为python列表变量名称的一部分
  2. 我希望每个列表都留在内存中以供进一步使用代码

我一直是这样的,它的工作,但蟒蛇名单变量似乎并没有留在记忆:

import arcpy, openpyxl 
from openpyxl import load_workbook, Workbook 

wb = load_workbook(r"Z:\Excel\LOOKUP_TABLES.xlsx") 

for i in wb.worksheets: 

    filepath = r"Z:\Excel\LOOKUP_TABLES.xlsx" + "\\" + i.title + "$" 
    varList = [] 
    with arcpy.da.SearchCursor(filepath, '*') as cursor: 
     for row in cursor: 
      varList.append(row[0]) 

    # This is the area I am struggling with. I can't seem to find a way to return 
    # each list into memory. I've tried the following code to dynamically create 
    # variable names from the name of the sheet so that each list has it's own 
    # variable. After the code has run, I'd just like to set a print statement 
    # (i.e. print variablename1) which will return the list contained in the variable 
    newList = str(i.title) + "List" 
    newList2 = list(varList) 
    print newList + " = " + str(newList2) 

我一直工作在这一段时间而且我毫不怀疑,在这一点上,我正在考虑我的解决方案,但我处于封锁状态。任何建议,欢迎!

+0

你解决了这个问题吗? – alecxe

回答

1

而不必养殖列表,使用字典,每片收集的数据:如果

import arcpy 
from openpyxl import load_workbook 

wb = load_workbook(r"Z:\Excel\LOOKUP_TABLES.xlsx") 

sheets = {} 
for i in wb.worksheets: 
    filepath = r"Z:\Excel\LOOKUP_TABLES.xlsx" + "\\" + i.title + "$" 
    with arcpy.da.SearchCursor(filepath, '*') as cursor: 
     sheets[i.title] = [row[0] for row in cursor] 

print sheets 
3

不知道它是最适合你的,但你可以使用大熊猫导入你的床单成一个数据帧。

from pandas.io.excel import ExcelFile 
filename = 'linreg.xlsx' 
xl = ExcelFile(filename) 

for sheet in xl.sheet_names: 
    df = xl.parse(sheet) 
    print df 
+0

我正在使用此确切方法,但代码在运行到空白工作表时崩溃。有什么想法吗? – bejota

相关问题