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 - ionic应用打包部署了,但是连接不上服务器,就连写一个a标签链接到百度都不可以2. dockerfile - 我用docker build的时候出现下边问题 麻烦帮我看一下3. css - 移动端 oppo 手机之 Border-radius4. boot2docker无法启动5. gosts内容是空的6. PHP单例模式7. css3 - 有好的Blog的CSS样式吗?8. java - 什么叫构建?求解答 ^.^9. css3 - 微信前端页面遇到的transition过渡动画的bug10. browsersync检测的静态页面只能用index.html命名,用demo.html就不能实时同步,检测动态页面的时候,比如wamp环境下,用browsersync能打开页面,但不能实现同步