Maison  >  Questions et réponses  >  le corps du texte

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包起来,以免程序中途停止。而且各个的处理方式不一样。这段代码要怎么写才合适才优雅?
为什么用优雅语言写出来的还是一坨......

天蓬老师天蓬老师2740 Il y a quelques jours700

répondre à tous(4)je répondrai

  • PHP中文网

    PHP中文网2017-04-18 10:25:29

    _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

    répondre
    0
  • PHP中文网

    PHP中文网2017-04-18 10:25:29

    Initialisez info, par exemple info=[0,0,0] Je pense que c'est assez élégant !

    répondre
    0
  • 黄舟

    黄舟2017-04-18 10:25:29

    Implémentation JS, les autres langages devraient être similaires.

    res = '';
    info.forEach(function(inf, i) {
      i === 1 && (res += '会话数' + inf);
      i === 2 && (res += '失效数' + inf);
      i === 3 && (res += '连接数' + inf);
    });

    répondre
    0
  • 阿神

    阿神2017-04-18 10:25:29

    L'utilisation de la fonction format est un meilleur choix que la concaténation de chaînes.

    res += "{type}   {count}".format(type = ["会话数", "失效数", "连接数"][i],count = info[i])

    répondre
    0
  • Annulerrépondre