您的位置:首頁技術文章
文章詳情頁

python - 怎么寫才合適才優雅

瀏覽:118日期:2022-09-07 14:57:47

問題描述

先上代碼

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])

標簽: Python 編程
相關文章:
国产综合久久一区二区三区