Re: [問題] 該怎麼用dict處理這個問題?

作者: SocketAM2 (AM2)   2015-04-27 23:19:54
counter_dict = dict()
with open(output_file, 'wb') as fo:
with open(file1, 'rb') as fi:
for line in fi.read().splitlines():
try:
pair = left, right = line.split('>') # format check
for item in pair:
try:
counter_dict[item] += 1
except:
counter_dict.setdefault(item, 1)
fo.write("{l}.{num_l}>{r}.{num_r}\n".format(
l = left, num_l = counter_dict[left],
r = right, num_r = counter_dict[right] )
except ValueError: # this line is not "X>Y"
# case 1: "too many values to unpack"
# case 2: "need more than 1 value to unpack"
fo.write('Invalid line: {original}\n'.format(original=line))
continue
except: # unexpected error
raise
能保證輸入的格式的話
外層的try、except可以拿掉 (最內層要留著)
但應該不會感覺到速度差異
沒有真的測過,只是練習一下語法
希望沒有錯太多,歡迎各位高手指正
※ 引述《Dong0129 (阿東)》之銘言:
: 標題: [問題] 該怎麼用dict處理這個問題?(附上code@@)
: 時間: Mon Apr 27 21:19:14 2015
:
: 各位版友好,
:
: 請問我該如何運用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
: .
: .
: .
:
:
作者: Dong0129 (阿東跟上面講的情況一樣b)   2015-04-27 23:48:00
您好,謝謝您的指點,我好像搞錯了setdefault的用途...

Links booklink

Contact Us: admin [ a t ] ucptt.com