Re: 刪除類似資料
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
→
03/13 19:41,
3年前
, 1F
03/13 19:41, 1F
→
03/13 19:41,
3年前
, 2F
03/13 19:41, 2F
推
03/13 19:43,
3年前
, 3F
03/13 19:43, 3F
→
03/13 19:43,
3年前
, 4F
03/13 19:43, 4F
→
03/14 00:13,
3年前
, 5F
03/14 00:13, 5F
→
03/14 00:14,
3年前
, 6F
03/14 00:14, 6F
→
03/14 00:14,
3年前
, 7F
03/14 00:14, 7F
推
03/14 10:14,
3年前
, 8F
03/14 10:14, 8F
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章
-2
11