Converting Python 3.6.5 List to a table

前端 未结 3 1488
滥情空心
滥情空心 2021-01-28 14:25

I am currently working on a project and I need help on converting a list to a table. I have figured it out one way but there has to be a shorter and a cleaner way of doing it an

相关标签:
3条回答
  • 2021-01-28 14:26

    Try to use one of many popular packages available to print tabular o/p. My suggestion is to use tabulate

    from tabulate import tabulate
    sales_persons_list = list('ABCDE')
    sales_amounts_list = list('12345')
    print (tabulate(zip(sales_persons_list, sales_amounts_list), tablefmt="plain"))
    

    Output

    A  1
    B  2
    C  3
    D  4
    E  5
    
    0 讨论(0)
  • 2021-01-28 14:37

    this code output equals your code output :)

    sales_persons_list = [input('What is the name of the sales person?: ') for i in range(5)]
    print(sales_persons_list)
    sales_amounts_list = [
        float(input('How much did {} make in sales?:'.format(sales_persons_list[i]))) for i in range(len(sales_persons_list))]
    print(sales_amounts_list)
    print("%-15s %-15s" %("Salespeople","Sales Amount"))
    for i in range(len(sales_amounts_list)):
        print("%-15s %-15s" %(sales_persons_list[i],sales_amounts_list[i]))
    print("%-15s %-15s" %("Totals", sum(sales_amounts_list)))
    

    show list as table code:

    print("%-15s %-15s" %("Salespeople","Sales Amount"))
    for i in range(len(sales_amounts_list)):
        print("%-15s %-15s"%(sales_persons_list[i],sales_amounts_list[i]))
    print("%-15s %-15s" %("Totals", sum(sales_amounts_list)))
    

    output

    Salespeople     Sales Amount
    a               1222.0
    aa              1111.0
    aaa             2222.0
    aaaaa           3333.0
    aaaaaa          1133.0
    Totals          9021.0
    
    0 讨论(0)
  • 2021-01-28 14:42

    Try this:

    def displaySalesReport(sales_persons_list, sales_amounts_list):
        Total_Sales = sum(sales_amounts_list)
        print("%-15s %-15s" %("Salespeople","Sales Amount"))
        for s_person, s_amount in zip(sales_persons_list, sales_amounts_list):
            print("%-15s %-15s" % (s_person, s_amount))
        print("%-15s %-15s" %("Totals", Total_Sales))
    

    This is a simplified version of your code, you could also use Python Pandas to create a table, Pandas is the best for data in tabular form but it provides much more than you need:

    import pandas as pd
    
    data = {'Salespeople': sales_persons_list, 'Sales Amount': sales_amounts_list}
    df = pd.DataFrame.from_dict(data)
    df.append({'Sales Amount': Total}, index="Total")
    print(df)
    

    My code is pseudo you have to modify it to fit your need.

    0 讨论(0)
提交回复
热议问题