0

我正在用 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'))

然后我得到这个列表:

在此处输入图像描述

4

1 回答 1

1

您应该将每个人的名字和姓氏都打包到一个列表中,然后将该列表附加到名称列表中:

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     │
╘═══════════╧═══════════════╛
于 2021-03-29T02:40:49.303 回答