【问题标题】:How to join these columns? (Automate the boring stuff Chapter 6 practice project)如何加入这些列? (自动化无聊的东西第6章练习项目)
【发布时间】:2019-10-08 22:57:05
【问题描述】:

练习题要求我将 tabledata 中的嵌套列表排列成右对齐的列,每个列都有一个嵌套列表。我已经想出了如何将每列中的每个单词正确对齐到列本身的正确长度,但我不知道如何将列连接到列表中,而不是仅仅将它们打印为一列。

我尝试通过提前迭代将for-loop 中的字符串连接起来(print(list[i]+list[i+1]+list[i+2]...etc),但当它再次循环并递增i 时,我不断收到index out of range 错误。

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

def longlen(strings):
    maximum = 0
    for s in strings:
        if len(s) > maximum:
            maximum = len(s)
    return(maximum)

def printTable(table):
    column_width = [0] * len(table)
    for i in range(len(table)):
        column_width[i] =longlen(table[i])
        for x in range(len(table[i])):
            print(table[i][x].rjust(column_width[i]))

printTable(tableData)

现在我得到了每个单词的正确右对齐,但我不知道如何在一个 4 高 x 3 宽的右对齐表格中输出它。

现在看起来像这样:

  apples
 oranges
cherries
  banana
Alice
  Bob
Carol
David
 dogs
 cats
moose
goose

我需要这个:

apples   Alice  dogs
oranges  Bob    cats
cherries Carol  moose
banana   David  goose

【问题讨论】:

  • 告诉我输出应该是什么?
  • 你能给出预期的输出样本吗?
  • 已编辑以包含所需的输出。列需要全部正确对齐,但在此处的文本编辑器中很难正确排列
  • 如果你已经解决了正确的理由,那么剩下要做的就是transpose一个列表列表。

标签: python for-loop printing


【解决方案1】:

你可以修改你的printTable()函数:

def printTable(table):
    column_width = [0] * len(table)
    for i in range(len(table)):
        column_width[i] =longlen(table[i])
    for x in range(len(table[0])):
        for i in range(len(table)):
            print(table[i][x].rjust(column_width[i]),end=' ')
        print()

主要变化是我适当地更改了您的xi 位置,以便您打印列表的“转置”。

【讨论】:

    【解决方案2】:

    这样的事情应该可以工作。只是为了好玩,我添加了一两个鸭子,该函数只会输出一个空白项,其中列的长度不同

    tableData = [['apples', 'oranges', 'cherries', 'banana'],
                 ['Alice', 'Bob', 'Carol', 'David'],
                 ['dogs', 'cats', 'moose', 'duck', 'duck', 'goose']]
    
    def printTable(table):
        # Get length of longest item in each column
        column_widths = [len(max(column, key=len)) for column in table]
        # Get longest column
        longest_col = len(max(table, key=len))
        # Major loop on each item in each nested list
        for j in range(longest_col):
            line = []
            # Nested loop over each nested list
            for i in range(len(table)):
                if j < len(table[i]):
                    line.append(table[i][j].rjust(column_widths[i]))
                else:
                    line.append(' '*column_widths[i])
            print('  '.join(line))
    
    printTable(tableData)
    

    输出:

      apples  Alice   dogs
     oranges    Bob   cats
    cherries  Carol  moose
      banana  David   duck
                      duck
                     goose
    

    【讨论】:

    • 我选择不使用任何内置函数,如zip 等,所以希望你能理解这里的逻辑
    【解决方案3】:

    您可以分两步完成:

    1. 遍历每一行并使用内置字符串方法rjust() 将每个单词用空格字符右对齐,以使所有单词的长度都与最长的单词相同。为此,您需要首先确定行中最长的单词,这可以使用 max()map() 函数的组合来完成。

    2. 使用内置的zip() 函数转置表格的行和列并打印其中的每一行。

    请注意,正如当前编写的那样,代码更改了table 的内容。如果您想避免这种情况,请先复制它。

    tableData = [['apples', 'oranges', 'cherries', 'banana'],
                 ['Alice', 'Bob', 'Carol', 'David'],
                 ['dogs', 'cats', 'moose', 'goose']]
    
    def printTable(table):
        for row in table:
            colwidth = max(map(len, row))
            row[:] = [word.rjust(colwidth) for word in row]
    
        for row in zip(*table):
            print(' '.join(row))
    
    
    printTable(tableData)
    

    【讨论】:

    • @Kind:哎呀。谢谢,陌生人 - 已修复。
    • 关闭,但ljust 还在里面:)
    • @Kind:哦,是的,代码也需要更改……再次感谢您的提醒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    相关资源
    最近更新 更多