以前にPythonで書いたコードを圧縮しようとしています。Excel ワークブック内の多数のルックアップ テーブルをループするコードがいくつかあります。ワークブックには、ルックアップ テーブルを含む約 20 のシートがあります。各ルックアップ テーブルの値をループして、独自のリストに追加したいと考えています。私の既存のコードは次のようになります。
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)
ヤダヤダ
そのコードを圧縮したい(おそらく関数内)。
解決すべき問題:
- シート名はすべて異なります。a)シートオブジェクトを取得し、b)Pythonリスト変数名の一部としてシート名を使用するために、Excelワークブックの各シートをループする必要があります
- コードに沿ってさらに使用するために、各リストをメモリに残しておきたい
私はこのようなことを試みてきましたが、これは機能しますが、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)
私はしばらくこれに取り組んできましたが、疑いの余地はありません。この時点で、私は自分の解決策を考えすぎていますが、ブロックされています。どんなお勧めも大歓迎です!