问题
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