python - 怎么写才合适才优雅
天蓬老师
天蓬老师 2017-04-18 10:23:29
0
4
687

先上代码

    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包起来,以免程序中途停止。而且各个的处理方式不一样。这段代码要怎么写才合适才优雅?
为什么用优雅语言写出来的还是一坨......

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回覆(4)
洪涛

雷雷

Ty80

初始化一下info 例如info=[0,0,0] 我覺得這個乾挺優雅的!

黄舟

JS實現,其它語言類似吧。

res = '';
info.forEach(function(inf, i) {
  i === 1 && (res += '会话数' + inf);
  i === 2 && (res += '失效数' + inf);
  i === 3 && (res += '连接数' + inf);
});
阿神

比起拼接字串使用format函數是更好的選擇。

res += "{type}   {count}".format(type = ["会话数", "失效数", "连接数"][i],count = info[i])
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!