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. 如何解決docker宿主機無法訪問容器中的服務?2. angular.js - $stateChangeSuccess事件在狀態跳轉的時候不執行?3. mysql 一個sql 返回多個總數4. angular.js - ionic2 瀏覽器跨域問題5. javascript - 螞蟻金服里的react Modal方法,是怎么把元素插入到頁面最后的6. 如何用筆記本上的apache做微信開發的服務器7. android - rxjava merge 返回Object對象數據如何緩存8. CSS3 畫如下圖形9. python - Scrapy存在內存泄漏的問題。10. java如何生成token?
