How to print values from lists in tabular format (python)?

谁都会走 提交于 2021-01-29 08:30:25

问题


Using python 2.7, I want to display the values in tabular format, without using pandas/prettytable. I am a beginner to python and am trying to learn.

Below is the values I have in list

listA = ["Alpha","Beta","gama","cat"]
data = [["A","B","C","D"],["E","F","G","H"],["I","J","K","L"],["M","N","O","P"]]

Expected output - to be displayed like below in tabular format :

Alpha  Beta  gama  cat    
A      B     C     D   
E      F     G     H     
I      J     K     L
M      N     O     P

I tried the following code, I am not getting the desired result:

def print_results_table(data, listA):
    str_l = max(len(t) for t in listA)
    print(" ".join(['{:>{length}s}'.format(t, length = str_l) for t in [" "] + listA]))

    for t, row in zip(listA, data):
        print(" ".join(['{:>{length}s}'.format(str(x), length = str_l) for x in [t] + row]))

print_results_table(data, listA)

回答1:


You're pretty close!

def print_results_table(data, listA):
    str_l = max(len(t) for t in listA)
    str_l += 2 # add two spaces between elements
    # print the titles
    for title in listA:
        print('{:<{length}s}'.format(title, length = str_l), end='')
    print()

    # print the values
    for row in data:
        for val in row:
            print('{:<{length}s}'.format(val, length = str_l), end='')
        print()

Output:

Alpha  Beta   gama   cat    
A      B      C      D      
E      F      G      H      
I      J      K      L      
M      N      O      P 


来源:https://stackoverflow.com/questions/55590145/how-to-print-values-from-lists-in-tabular-format-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!