作者SocketAM2 (AM2)
看板Python
标题Re: [问题] 该怎麽用dict处理这个问题?
时间Mon Apr 27 23:19:54 2015
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
: .
: .
: .
:
: --
:
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 220.137.109.243
: ※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1430140757.A.DBB.html
: → SocketAM2: 这是在帮版友做智力测验吗? 04/27 21:36
:
: 不是@@因为我对於dict的用法还不太熟,
:
: 因此想要请教其他版友的写法为何
: ※ 编辑: Dong0129 (220.137.109.243), 04/27/2015 21:42:22
: → SocketAM2: 看了5分钟才懂 我果然是笨蛋 04/27 21:41
:
: ...应该是我表达能力不够好...下次会用比较好的举例方式...
: ※ 编辑: Dong0129 (220.137.109.243), 04/27/2015 21:52:33
: 推 mars90226: 这个问题跟你上次问得很像啊? 04/27 22:06
: → mars90226: #1LBrjrc0 (Python) 04/27 22:07
:
: 嗯嗯,但有个小地方不同,
: 上次是如果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
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 122.116.23.186
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1430147997.A.45D.html
1F:推 Dong0129: 您好,谢谢您的指点,我好像搞错了setdefault的用途... 04/27 23:48
2F:→ Dong0129: 输出时.的左边并不是放原本的item,而是要放item种类@@ 04/28 11:01