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實現(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. debian - docker依賴的aufs-tools源碼哪里可以找到啊?2. dockerfile - 我用docker build的時候出現(xiàn)下邊問題 麻煩幫我看一下3. angular.js使用$resource服務把數(shù)據(jù)存入mongodb的問題。4. docker gitlab 如何git clone?5. docker 下面創(chuàng)建的IMAGE 他們的 ID 一樣?這個是怎么回事????6. macos - mac下docker如何設(shè)置代理7. javascript - 連續(xù)點擊觸發(fā)mouseleave事件8. docker網(wǎng)絡(luò)端口映射,沒有方便點的操作方法么?9. docker start -a dockername 老是卡住,什么情況?10. docker api 開發(fā)的端口怎么獲取?

網(wǎng)公網(wǎng)安備