簡體   English   中英

使用正則表達式匹配從列表中刪除多個元素

[英]Remove multiple elements from list using regex matching

我有一個 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

Output:

['India', 'Brazil', 'Czech', 'Italy', 'Hungary', 'Poland']

由於我使用 4 條語句只是為了收集要刪除的工作表的名稱,所以我希望找到一種更簡潔的方法來完成相同的任務。

在我看來,你所擁有的似乎很好。 另一種選擇是檢查每個工作表名稱是否包含您的單詞。 如果沒有,請將其保存在列表中:

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])]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM