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. html5 - vue-cli 装好了 新建项目的好了,找不到项目是怎么回事?2. 网页动画等过渡效果,CSS3 transitions 和 jQuery animations 谁实现的性能更好?3. 用CSS3 box-sizing 属性实现两个并排的容器,如果想让容器中间有间隔该如何实现4. python3.x - python 中的maketrans在utf-8文件中该怎么使用5. javascript - 一排三个框,各个框的间距是15px,距离外面的白框间距也是15px,这个css怎么写?6. node.js - webpack 配置文件 运行出错7. mysql - C#连接数据库时一直这一句出问题int i = cmd.ExecuteNonQuery();8. javascript - hexo可以配置文章文件名为随机数么?9. css - ul ol前边的标记如何调整样式呢10. python - 用urllib抓取网页上的下载链接,目标文件是xls形式,但发现抓下来的xls是空表,里面只有一句报错信息,求帮助。

网公网安备