![](/img/trans.png)
[英]how to show specific columns from a list, tabulate and print them on the console
[英]Python Tabulate - How to print vertically list with values from an input
我正在 Python 中制作一個控制台程序,用戶可以在其中向多個列表添加多個值並創建一個通訊錄。 我已經將所有數據放在了不同的列表中,現在我需要使用 TABULATE 模塊將這些數據打印到表格中。
我可以打印這些數據,但好像我不想向用戶顯示他們的通訊錄,因為在打印時,表格在垂直單行中向我顯示了 NAMES 字段,所有名稱用逗號分隔,而不是下面的一個另一個應該是。
我怎樣才能解決這個問題? (在主列表中,是名稱和姓氏之間的合並,這是我想要打印的一些數據。
from tabulate import tabulate
start = True
names = []
lastnames = []
while(start):
print("***************************************")
print("1: Add the contact name: ")
print("2: Add the lastname for the contact: ")
print("")
op = input("Which option you want to do?: ")
if(op == "1"):
print("\n ADDING")
name = input("Please, type the name of the contact: ")
names.append(name)
lastname = input("Now, please type the lastname: ")
lastnames.append(lastname)
print("")
if(op == "2"):
print("EXIT")
start = False
nameStr = "".join(names) # Get the list in a str
lastStr = "".join(lastnames) # Get the list in a str
mainList = [[nameStr, lastStr]] # Main list, with the str data
heads = ["NAMES: ", "LASTNAMES: "] # Headers to the tabulate module
print(" ")
print(tabulate(mainList, headers=heads, tablefmt='fancy_grid', stralign='center'))
然后我得到這個列表:
您應該將每個人的名字和姓氏都打包到一個列表中,然后將 append 打包到名稱列表中:
from tabulate import tabulate
start = True
names = []
while(start):
print("***************************************")
print("1: Add the contact name: ")
print("2: Exit ")
print("")
op = input("Which option you want to do?: ")
if(op == "1"):
print("\n ADDING")
name = input("Please, type the name of the contact: ")
lastname = input("Now, please type the lastname: ")
names.append([name, lastname])
print("")
if(op == "2"):
print("EXIT")
start = False
heads = ["NAMES: ", "LASTNAMES: "] # Headers to the tabulate module
print(" ")
print(tabulate(names, headers=heads, tablefmt='fancy_grid', stralign='center'))
╒═══════════╤═══════════════╕
│ NAMES: │ LASTNAMES: │
╞═══════════╪═══════════════╡
│ Louis │ Smith │
├───────────┼───────────────┤
│ Gerard │ Taylor │
╘═══════════╧═══════════════╛
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.