我有一個 Excel 作業簿,其中作業表名稱為國家。除了這些作業表之外,還有一些我不想處理的作業表。因此,我試圖消除這些作業表,只保留作業表名稱為國家名稱的作業表。
下面是我正在使用的代碼,它正在完成作業:
all_sheets = xl.sheet_names # see all sheet names
entries_to_remove_1 = ['Information', 'Summary', 'Template', 'Source', 'BOW']
entries_to_remove_2 = list(filter(lambda x: 'Annual' in x, all_sheets))
entries_to_remove_3 = list(filter(lambda x: 'Quarterly' in x, all_sheets))
entries_to_remove_4 = list(filter(lambda x: 'WIP' in x, all_sheets))
entries_to_remove = entries_to_remove_1 entries_to_remove_2 entries_to_remove_3 entries_to_remove_4
entries_for_replacement = [i for i in all_sheets if i not in entries_to_remove]
all_sheets = list(set(entries_for_replacement))
all_sheets
輸出:
['India', 'Brazil', 'Czech', 'Italy', 'Hungary', 'Poland']
由于我使用 4 個陳述句來收集要洗掉的作業表的名稱,因此我希望找到一種更簡潔的方法來完成相同的任務。
uj5u.com熱心網友回復:
在我看來,你所擁有的似乎很好。另一種選擇是檢查每個作業表名稱是否包含您的單詞。如果沒有,請將其保存在串列中:
words = ['Information', 'Summary', 'Template', 'Source', 'BOW', 'Annual', 'Quarterly', 'WIP']
all_sheets = [sheet for sheet in all_sheets if all([word not in sheet for word in words])]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/491950.html
下一篇:在熊貓交叉表中使用自定義列串列
