首页 > 解决方案 > 在不同的列中打印列表

问题描述

我对 Python 很陌生,现在我正在努力在列中打印我的列表。它只在一列中打印我的列表,但我希望它打印在 4 个不同的标题下。我知道我错过了一些东西,但似乎无法弄清楚。任何建议将不胜感激!

def createMyList():
    myAgegroup = ['20 - 39','40 - 59','60 - 79']
    mygroupTitle = ['Age','Underweight','Healthy','Overweight',]
    myStatistics = [['Less than 21%','21 - 33','Greater than 33%',],['Less than 23%','23 - 35','Greater than 35%',],['Less than 25%','25 - 38','Greater than 38%',]]
    printmyLists(myAgegroup,mygroupTitle,myStatistics)
    return

def printmyLists(myAgegroup,mygroupTitle,myStatistics):
    print(':    Age    :    Underweight    :    Healthy    :    Overweight    :')

    for count in range(0, len(myAgegroup)):
        print(myAgegroup[count])

    for count in range(0, len(mygroupTitle)):
        print(mygroupTitle[count])

    for count in range(0, len(myStatistics)):
        print(myStatistics[0][count])
        return

createMyList()

标签: python-3.x

解决方案


要在漂亮的列中打印数据很高兴知道 Format Specification Mini-Languag ( doc )。此外,要将数据组合在一起,请查看zip()内置函数 ( doc )。

例子:

def createMyList():
    myAgegroup = ['20 - 39','40 - 59','60 - 79']
    mygroupTitle = ['Age', 'Underweight','Healthy','Overweight',]
    myStatistics = [['Less than 21%','21 - 33','Greater than 33%',],['Less than 23%','23 - 35','Greater than 35%',],['Less than 25%','25 - 38','Greater than 38%',]]
    printmyLists(myAgegroup,mygroupTitle,myStatistics)

def printmyLists(myAgegroup,mygroupTitle,myStatistics):

    # print the header:
    for title in mygroupTitle:
        print('{:^20}'.format(title), end='')

    print()

    # print the columns:
    for age, stats in zip(myAgegroup, myStatistics):
        print('{:^20}'.format(age), end='')
        for stat in stats:
            print('{:^20}'.format(stat), end='')
        print()

createMyList()

印刷:

    Age             Underweight           Healthy            Overweight     
  20 - 39          Less than 21%          21 - 33         Greater than 33%  
  40 - 59          Less than 23%          23 - 35         Greater than 35%  
  60 - 79          Less than 25%          25 - 38         Greater than 38%  

推荐阅读