Re: 刪除類似資料

看板Python作者 (Naked Bear)時間3年前 (2021/03/12 16:02), 編輯推噓1(100)
留言1則, 1人參與, 3年前最新討論串2/3 (看更多)
※ 引述《crm123 (CRM)》之銘言: : 小弟用list裝資料 資料內容類似如下 : 10day.png : 20day.png : 20day-1.png : 30day.png : 40day.png : 40day-1.png : 40day-2.png : 想要做到能夠刪除類似資料(開頭的10、20) : 然後重複的(20兩筆留-1的、40留-2) : 想問有沒有什麼方法能夠達到 : 謝謝 : ----- : Sent from JPTT on my iPhone 小弟目前自學四個月,練習寫了一下 - - - file_dict = {'10day.png': '10day.png內容 要留', '20day.png': '20day.png內容 不留', '20day-1.png': '20day-1.png內容 要留', '30day.png': '30day.png內容 要留', '40day.png': '40day.png內容 不留', '40day-1.png': '40day-1.png內容 不留', '40day-2.png': '40day-2.png內容 要留' } file_name_list_raw = list(file_dict.keys()) file_name_list_del = [] for i in file_name_list_raw: if '-' in i: extension = i.split('.')[-1] serial = int(i.split('-')[-1].split('.')[0]) name = i.split('-')[0] if serial == 1: file_name_list_del.append(name+'.'+extension) else: file_name_list_del.append(name+'-'+str(serial-1)+'.'+extension) for i in file_name_list_del: del file_dict[i] print(file_dict) - - - 最後輸出結果是 {'10day.png': '10day.png內容 要留', '20day-1.png': '20day-1.png內容 要留', '30day.png': '30day.png內容 要留', '40day-2.png': '40day-2.png內容 要留'} 如果要只把檔案內容存成list的話,再加一條 變數 = list(file_dict.values()) 就可以了 感覺文字處理的部分如果用正規表示式的話應該可以更好, 希望能拋磚引玉,看看板上大大更好的寫法 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.136.169.76 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1615536167.A.484.html

03/12 16:49, 3年前 , 1F
我來試試看怎樣改成我需要的 謝謝
03/12 16:49, 1F
文章代碼(AID): #1WIo0dI4 (Python)
討論串 (同標題文章)
本文引述了以下文章的的內容:
4
13
以下文章回應了本文
2
8
完整討論串 (本文為第 2 之 3 篇):
4
13
2
8
文章代碼(AID): #1WIo0dI4 (Python)