python - 怎么写才合适才优雅
问题描述
先上代码
try:res+='会话数<span style=’color: blue;’> '+str(info[1]).strip(’n’)+'</span><br>' except Exception,e:print e try:res+='失效数<span style=’color: blue;’> '+str(info[2]).strip(’n’)+'</span><br>' except Exception,e:print e try:res+='连接数<span style=’color: blue;’> '+str(info[3]).strip(’n’).strip(’t’)+'</span><br>' except Exception,e:print e
上面的info[1]、info2[2]、info3[3],可能并不存在,所以我用try包起来,以免程序中途停止。而且各个的处理方式不一样。这段代码要怎么写才合适才优雅?为什么用优雅语言写出来的还是一坨......
问题解答
回答1:_list = (’会话数’, ’失效数’, ’连接数’)for index, c in enumerate(_list): try:res+='{}<span style=’color: blue;’> '.format(c) + str(info[index + 1]).strip(’n’)'</span><br>' except Exception,e:print e回答2:
初始化一下info 例如info=[0,0,0] 我感觉这个干挺优雅的!
回答3:JS实现,其它语言类似吧。
res = ’’;info.forEach(function(inf, i) { i === 1 && (res += ’会话数’ + inf); i === 2 && (res += ’失效数’ + inf); i === 3 && (res += ’连接数’ + inf);});回答4:
比起拼接字符串使用format函数是一个更好的选择。
res += '{type} {count}'.format(type = ['会话数', '失效数', '连接数'][i],count = info[i])
相关文章:
1. android - RxJava 中有根据条件执行不同函数的操作符吗?2. javascript - html5的data属性怎么指定一个function函数呢?3. html5 - 为什么使使用vue cli 脚手架,post-css 没有自动对css3属性自动添加浏览器前缀呢?4. angular.js - 输入邮箱地址之后, 如何使其自动在末尾添加分号?5. 管理员信息修改时的密码问题6. python - Scrapy存在内存泄漏的问题。7. java如何生成token?8. javascript - 后台管理系统左侧折叠导航栏数据较多,怎么样直接通过搜索去定位到具体某一个菜单项位置,并展开当前菜单9. javascript - 如何使用nodejs 将.html 文件转化成canvas10. mysql - 电商如何存储营业额数据
