python - 怎么寫才合適才優(yōu)雅
問題描述
先上代碼
try:res+='會話數(shù)<span style=’color: blue;’> '+str(info[1]).strip(’n’)+'</span><br>' except Exception,e:print e try:res+='失效數(shù)<span style=’color: blue;’> '+str(info[2]).strip(’n’)+'</span><br>' except Exception,e:print e try:res+='連接數(shù)<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包起來,以免程序中途停止。而且各個的處理方式不一樣。這段代碼要怎么寫才合適才優(yōu)雅?為什么用優(yōu)雅語言寫出來的還是一坨......
問題解答
回答1:_list = (’會話數(shù)’, ’失效數(shù)’, ’連接數(shù)’)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] 我感覺這個干挺優(yōu)雅的!
回答3:JS實(shí)現(xiàn),其它語言類似吧。
res = ’’;info.forEach(function(inf, i) { i === 1 && (res += ’會話數(shù)’ + inf); i === 2 && (res += ’失效數(shù)’ + inf); i === 3 && (res += ’連接數(shù)’ + inf);});回答4:
比起拼接字符串使用format函數(shù)是一個更好的選擇。
res += '{type} {count}'.format(type = ['會話數(shù)', '失效數(shù)', '連接數(shù)'][i],count = info[i])
相關(guān)文章:
1. angular.js - 關(guān)于$apply()2. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問題。3. MySQL數(shù)據(jù)庫中文亂碼的原因4. dockerfile - 我用docker build的時候出現(xiàn)下邊問題 麻煩幫我看一下5. nignx - docker內(nèi)nginx 80端口被占用6. android-studio - Android Studio 運(yùn)行項(xiàng)目的時候一堆警告,跑步起來???7. dockerfile - [docker build image失敗- npm install]8. angular.js - Ionic 集成crosswalk后生成的apk在android4.4.2上安裝失?。浚??9. mysql - 新浪微博中的關(guān)注功能是如何設(shè)計(jì)表結(jié)構(gòu)的?10. 如何解決Centos下Docker服務(wù)啟動無響應(yīng),且輸入docker命令無響應(yīng)?
