为了账号安全,请及时绑定邮箱和手机立即绑定

Python将字符串插入字典

Python将字符串插入字典

守着星空守着你 2021-03-12 19:15:09
我打开一个.txt文件并阅读.txt contents = html_log:Bob -1.2 -0.25 4:53 1 0:02 2 1 3 html_log:John 26.6 0.74 36:00 -4 3 25 26 1:57 74 12 16 -1.11 html_log:Bob -1.2 -0.25 4:53 1 0:04 2 1 3 change = str(textfile)pattern2 = re.compile("html_log:(?P<name>[^ ]*)(?: [^\s]+){4} (?P<score>[^ ]*)")try:    mylist2=sorted(pattern2.findall(change), key=lambda x: float(x[1]), reverse=True)except ValueError:    mylist2=sorted(pattern2.findall(change), key=lambda x: float('0'), reverse=True)产生mystr = ('Bob', '0:02'), ('John', '3'),('Bob', '0:02')我正在尝试做的是找出该值是否不是有效的int。0:02,如果不是,则将其替换为0。我正在尝试产生以下结果:('Bob', '0'), ('John', '3')我试图将[k]和[v]放入字典中,并添加[v]的值,但是由于数字无效,它不起作用。mic = defaultdict(int)for k,v in mylist2:    mic[k] += re.sub(' ^\d*:\d*','0',v)不工作。并产生typeerrorTraceback (most recent call last):  File "C:/Python26/myfile.py", line 44, in <module>    mic[k] += re.sub(' ^\d*:\d*','0',v)TypeError: unsupported operand type(s) for +=: 'int' and 'str'
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 245 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号