python - 怎么寫才合適才優(yōu)雅
問題描述
先上代碼
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包起來,以免程序中途停止。而且各個的處理方式不一樣。這段代碼要怎么寫才合適才優(yōu)雅?為什么用優(yōu)雅語言寫出來的還是一坨......
問題解答
回答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] 我感覺這個干挺優(yōu)雅的!
回答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. javascript - 關于定時器 與 防止連續(xù)點擊 問題2. javascript - 求助關于js正則問題3. objective-c - ios百度地圖定位問題4. javascript - 求助這種功能有什么好點的插件?5. javascript - js 有什么優(yōu)雅的辦法實現在同時打開的兩個標簽頁間相互通信?6. 為何 localStorage、sessionStorage 屬于html5的范疇,但是為何 IE8卻支持?7. html5 - rudy編譯sass的時候有中文報錯8. html - css 如何添加這種邊框?9. javascript - node.js服務端渲染解疑10. 微信開放平臺 - Android調用微信分享不顯示
