我試圖壓縮一些先前在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)
內容非常重要
我想壓縮代碼(也許在一個函數)。
問題需要解決:
- 表的名稱都不同。我需要遍歷Excel工作簿中的每個工作表,以便a)抓取工作表對象和b)使用工作表名稱作爲python列表變量名稱的一部分
- 我希望每個列表都留在內存中以供進一步使用代碼
我一直是這樣的,它的工作,但蟒蛇名單變量似乎並沒有留在記憶:
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)
我一直工作在這一段時間而且我毫不懷疑,在這一點上,我正在考慮我的解決方案,但我處於封鎖狀態。任何建議,歡迎!
你解決了這個問題嗎? – alecxe