【问题标题】:Lining up strings with list object lengths用列表对象长度排列字符串
【发布时间】:2013-08-09 18:14:44
【问题描述】:

我有这个函数可以比较我从 txt 文件中提取的统计信息,因此它们是静态的。我试图想办法将每个种族/亚种的统计数据与名称对齐。这是来源:

def compare():
    print('------ Compare Race Stats ------')
    comp1 = query()
    comp2 = query()
    comp1 = stats(comp1[0],comp1[1])
    comp2 = stats(comp2[0],comp2[1])
    print('{} - {} | {} - {}'
          .format(comp1[0][0],comp1[0][1],comp2[0][0],comp2[0][1]))
    for i in range(len(comp1[1])):
        print('{}{}{}{}'.format(' '*round(len(comp1[0][0])+len(comp1[0][1])/5),comp1[1][i],
                                ' '*round(len(comp2[0][0])+2+len(comp2[0][1])/5),comp2[1][i]))

query() 询问您想要什么种族/子种族并为每个种族返回字符串。 stats() 获取种族/子种族名称,从 txt 文件中提取并返回统计信息和名称。第二个空格计算中的+2 是我对第一个打印语句(print('{} - {} | {} - {}')的计算,这是一个猜测。输出看起来还不错,我认为空间计算有点聪明(我是菜鸟),但我不禁想知道 Stack Overflow 会说什么。是否有某些公认的方式来排列各种输出。

这是一些输出,有 10 种不同的种族/子种族:

Elezen - Duskwight | Hyur - Midlander
        STR : 20        STR : 21
        DEX : 20        DEX : 19
        VIT : 19        VIT : 20
        INT : 23        INT : 21
        MND : 20        MND : 18
        PIE : 18        PIE : 21

Mi'Qote - Seekers of the Sun | Mi'Qote - Keepers of the Moon
           STR : 21             STR : 18
           DEX : 22             DEX : 21
           VIT : 20             VIT : 17
           INT : 18             INT : 19
           MND : 19             MND : 23
           PIE : 20             PIE : 22

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    经过一番研究,我发现了 rjustljust str 函数:

    def compare():
        print("------ Compare Race Stats ------")
        comp1 = query()
        comp2 = query()
        comp1 = stats(comp1[0], comp1[1])
        comp2 = stats(comp2[0], comp2[1])
        print("{} - {} | {} - {}"
              .format(comp1[0][0], comp1[0][1], comp2[0][0], comp2[0][1]))
        for i in range(len(comp1[1])):
            print("{} {} {}".format(comp1[1][i].rjust(len(comp1[0][0]+comp1[0][1])+3),
                                    "|", comp2[1][i]))
    

    这是输出:

    Roegadyn - Hellsguard | Elezen - Duskwight
                 STR : 20 | STR : 20
                 DEX : 17 | DEX : 20
                 VIT : 21 | VIT : 19
                 INT : 20 | INT : 23
                 MND : 22 | MND : 20
                 PIE : 20 | PIE : 18
    
    Mi'Qote - Keepers of the Moon | Roegadyn - Hellsguard
                         STR : 18 | STR : 20
                         DEX : 21 | DEX : 17
                         VIT : 17 | VIT : 21
                         INT : 19 | INT : 20
                         MND : 23 | MND : 22
                         PIE : 22 | PIE : 20
    

    我很抱歉问了一个我应该在发帖之前回答自己的问题,至少我能做的很明显给出一个答案。

    【讨论】:

      猜你喜欢
      • 2018-02-23
      • 2014-02-13
      • 2020-09-25
      • 2011-10-17
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 2011-02-04
      相关资源
      最近更新 更多