[問題] 該怎麼用dict處理這個問題?(附上code)

看板Python作者 (阿東)時間9年前 (2015/04/27 21:19), 9年前編輯推噓2(2010)
留言12則, 5人參與, 最新討論串1/1
各位版友好, 請問我該如何運用dict轉換以下需求? file1: 2>4 1>2 2>3 3>5 3>1 1>4 4>2 . . . 轉換成: file2: 1.1>2.1 3.1>1.2 1.3>4.1 4.2>5.1 4.3>3.2 3.3>2.2 2.3>1.4 . . . 即.左邊的數字為第幾種,而.右邊的數字為出現幾次, 麻煩各位大大幫幫忙了! 目前撰寫的程式為: rfd=open(file1,"r") wfd.open(file2,"w") dict_file=dict() num={} seq={} for line in rfd.read().splitlines(): item1,item2=line.split('>') for item in (item1,item2): if not item in num: num[item]=1 seq[item]=len(num.keys()) else: num[item]+=1 dict_file.setdefault(item,str(seq[item])+"."+str(num[item])) wfd.write(dict_file[item1]+'>'+dict_file[item2]) rfd.close() wfd.close() file2的內容: 1.1>2.1 3.1>1.1 1.1>4.1 . . . 好像在執行dict_file.setdefault那ㄧ句寫不進去... 請問我有哪裡寫錯嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.137.109.243 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1430140757.A.DBB.html

04/27 21:36, , 1F
這是在幫版友做智力測驗嗎?
04/27 21:36, 1F
不是@@因為我對於dict的用法還不太熟, 因此想要請教其他版友的寫法為何 ※ 編輯: Dong0129 (220.137.109.243), 04/27/2015 21:42:22

04/27 21:41, , 2F
看了5分鐘才懂 我果然是笨蛋
04/27 21:41, 2F
...應該是我表達能力不夠好...下次會用比較好的舉例方式... ※ 編輯: Dong0129 (220.137.109.243), 04/27/2015 21:52:33

04/27 22:06, , 3F
這個問題跟你上次問得很像啊?
04/27 22:06, 3F

04/27 22:07, , 4F
04/27 22:07, 4F
嗯嗯,但有個小地方不同, 上次是如果file1有相同的資料,file2就不給新的代號, 這次想要做到即使是相同資料,也會給新的代號 對於dict的概念還不夠熟,目前也正在寫程式, 謝謝您! ※ 編輯: Dong0129 (220.137.109.243), 04/27/2015 22:13:03 ※ 編輯: Dong0129 (220.137.109.243), 04/27/2015 22:42:30 ※ 編輯: Dong0129 (220.137.109.243), 04/27/2015 22:42:46 ※ 編輯: Dong0129 (220.137.109.243), 04/27/2015 22:53:31

04/28 09:52, , 5F

04/28 10:47, , 6F
謝謝你們,有好多種寫法啊...慢慢研究,謝謝!! ※ 編輯: Dong0129 (220.137.114.148), 04/28/2015 11:00:30

04/28 14:54, , 7F
setdefault 那行改成
04/28 14:54, 7F

04/28 14:54, , 8F
dict_file[item]=str(seq[item]) + "." + str(num[item])
04/28 14:54, 8F

04/28 14:54, , 9F
就行了吧
04/28 14:54, 9F

04/28 14:56, , 10F
你用 setdefault 的話根本不會更新 所以最後得到都是 x.1
04/28 14:56, 10F
嗯...我ㄧ直以為setdefault是設定item對應","之後的資料,後來才發現原來是沒有item 時才設定... ※ 編輯: Dong0129 (220.137.114.148), 04/28/2015 15:00:48

04/28 15:00, , 11F
d.setdefaut(k, v) 是說去看d的key有無k 有的話回傳d[k]
04/28 15:00, 11F

04/28 15:00, , 12F
沒的話就做 d[k] = v 然後回傳 v
04/28 15:00, 12F
謝謝您! ※ 編輯: Dong0129 (220.137.114.148), 04/28/2015 15:03:53
文章代碼(AID): #1LFZTLsx (Python)