[问题] 该怎么用dict处理这个问题?(附上code)

楼主: Dong0129 (阿东跟上面讲的情况一样b)   2015-04-27 21:19:14
各位版友好,
请问我该如何运用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那ㄧ句写不进去...
请问我有哪里写错吗?
作者: SocketAM2 (AM2)   2015-04-27 21:36:00
这是在帮版友做智力测验吗?看了5分钟才懂 我果然是笨蛋
作者: mars90226 (火星人)   2015-04-27 22:06:00
这个问题跟你上次问得很像啊?#1LBrjrc0 (Python)
作者: eight0 (欸XD)   2015-04-28 09:52:00
作者: penguin7272 (企鹅)   2015-04-28 10:47:00
作者: gh40402   2015-04-28 14:54:00
setdefault 那行改成dict_file[item]=str(seq[item]) + "." + str(num[item])就行了吧你用 setdefault 的话根本不会更新 所以最后得到都是 x.1d.setdefaut(k, v) 是说去看d的key有无k 有的话回传d[k]没的话就做 d[k] = v 然后回传 v

Links booklink

Contact Us: admin [ a t ] ucptt.com