看板 Python 關於我們 聯絡資訊
png = '''10day.png 20day.png 20day-1.png 30day.png 40day.png 40day-1.png 40day-2.png'''.split('\n') dic = {} for p in png: ....prefix = p.split('day')[0] ....suffix = int(p.split('day')[-1].replace('.png', '').replace('-', '') or 0) ....dic[prefix] = max(dic.get(prefix, 0), suffix) print(dic) # {'10': 0, '20': 1, '30': 0, '40': 2} res = [f'{k}day'+(f'-{v}' if v else '') + '.png' for k, v in dic.items()] print(res) # ['10day.png', '20day-1.png', '30day.png', '40day-2.png'] 我會這樣做 給你參考 ※ 引述《tzouandy2818 (Naked Bear)》之銘言: : ※ 引述《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), 來自: 101.137.237.55 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1615580642.A.34C.html ※ 編輯: LP9527 (101.137.237.55 臺灣), 03/13/2021 05:04:38
tzouandy2818: 其實我是不知道他要處理的資料到底是檔名還是檔案內 03/13 19:41
tzouandy2818: 容 才會用dict的方式 key放檔名 value放檔案內容 03/13 19:41
crm123: png就是副檔名了 主要是要判斷檔名有沒有- 有的話就找數字 03/13 19:43
crm123: 最高的 其他剔除 03/13 19:43
tzouandy2818: 我跟他的寫法在副檔名的部分都沒問題啊 03/14 00:13
tzouandy2818: 我是說 不知道你在list裡要放的資料到底是xxxx.png 03/14 00:14
tzouandy2818: 這個檔名 還是xxxx.png這張圖片 03/14 00:14
crm123: 放檔名而已 03/14 10:14