如何在Python中使用Pretty Table从多个列表中打印数据?

10
我对Python编程相对较新,使用的是Python 3.x版本,正在开发一款理发店收银系统,管理员将有特权添加服务及其对应价格。我正在使用Pretty Table库来打印一个包含服务ID、服务和价格的表格。
以下是我的代码:
from prettytable import PrettyTable
import random

serviceID = []
services = []
price = []
x = PrettyTable()

x.add_column("ServiceID",[serviceID])
x.add_column("Service", [services])
x.add_column("Price", [price])

while True:
try:

     ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
     serviceID.append(ID) #Generates unique ID for each service
     prompt1 = input("Please add a service name to the list\n")
     services.append(prompt1)

     prompt2 = input("Please enter a price for the service\n")
     prompt2 == int(prompt2)
     price.append(prompt2)

     print(x)


except ValueError:
    print("Please enter valid type")
    continue

当我输入第一个服务和价格时,输出为:

+-----------+---------+--------+
| ServiceID | Service | Price  |
+-----------+---------+--------+
|   [9880]  | ['box'] | ['90'] |
+-----------+---------+--------+
当我输入第二个服务和价格时,输出结果是这样的:
+---------------+-----------------+--------------+
|   ServiceID   |     Service     |    Price     |
+---------------+-----------------+--------------+
| [9880, 47612] | ['box', 'trim'] | ['90', '80'] |
+---------------+-----------------+--------------+

我希望输出是这样的:

+---------------+-----------------+--------------+
|   ServiceID   |     Service     |    Price     |
+---------------+-----------------+--------------+
|  9880         |      box        |       90     |
|  47612        |     trim        |       80     |
+---------------+-----------------+--------------+

有谁知道如何实现这个? 任何帮助将不胜感激。


你需要使用"\n".join(your_sublist)将列表中的字符串连接起来。 - Padraic Cunningham
2个回答

4
我们可以通过使用 add_row 方法将行添加到 PrettyTable 对象中。 示例:
>>> from prettytable import PrettyTable
>>> import random
>>> 
>>> x = PrettyTable(["ServiceID", "Service", "Price"])
>>> 
>>> while True:
...     #- Get value
...     ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
...     prompt1 = raw_input("Please add a service name to the list\n")
...     try:
...         #- Type Casting.
...         prompt2 = int(raw_input("Please enter a price for the service\n"))
...     except ValueError:
...         print("Please enter valid type")
...         continue
...     #- Add row
...     x.add_row([ID, prompt1, prompt2])
...     #- Ask user to Continue or not.
...     choice = raw_input("Continue yes/ no:").lower()
...     if not(choice=="yes" or choice=="y"):
...         break
... 
Please add a service name to the list
2
Please enter a price for the service
3
Continue yes/ no:y
Please add a service name to the list
4
Please enter a price for the service
6
Continue yes/ no:y
Please add a service name to the list
5
Please enter a price for the service
7
Continue yes/ no:n
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|    8680   |    4    |   6   |
|   51188   |    5    |   7   |
+-----------+---------+-------+
>>> 

删除行:

使用 del_row() 方法。我们需要传递要删除的行的索引。

>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|    8680   |    4    |   6   |
|   51188   |    5    |   7   |
+-----------+---------+-------+
>>> x.del_row(1)
>>> print x
+-----------+---------+-------+
| ServiceID | Service | Price |
+-----------+---------+-------+
|   38515   |    2    |   3   |
|   51188   |    5    |   7   |
+-----------+---------+-------+

如果我们提供的索引值大于总行数,就会引发异常,需要在您的代码中处理该异常。

异常是:

>>> x.del_row(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/prettytable.py", line 832, in del_row
    raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows)))
Exception: Cant delete row at index 10, table only has 2 rows!

注意:

  1. 在Python 2.x中使用raw_input()

  2. 在Python 3.x中使用input()


谢谢Vivek和Padraic。 如何从表格中删除一行? 我尝试像这样索引表格del[2],但它不起作用。 - mabishi
@ElizabethMabishi:使用 del_row 方法。传入我们想要删除的行的索引。我会在答案中添加。 - Vivek Sable
对于我之前的问题,我找到了一种绕过访问单个元素的方法。这是我做的:def log_service(): while True: try: response3 = input("请使用ServiceID从列表中选择服务。\n") response3 = int(response3) y = (x[response3:(response3 + 1)]) #写入报告表。工作但不存储以前记录的值。即每次都重新开始是否有像附加列表这样的方法或者我可以使用另一个方法来在每次调用fx时将行添加到新表中?抱歉,它没有创建代码块。 - mabishi

0

我通过始终在while循环内创建类prettytable的新实例来实现这一点。

from prettytable import PrettyTable
import random

serviceID = []
services = []
price = []

while True:
    try:
        x = PrettyTable()

        ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
        serviceID.append(ID) #Generates unique ID for each service

        prompt1 = input("Please add a service name to the list\n")
        services.append(prompt1)

        prompt2 = input("Please enter a price for the service\n")
        prompt2 == int(prompt2)
        price.append(prompt2)

        x.add_column("ServiceID", serviceID)
        x.add_column("Service", services)
        x.add_column("Price", price)

        print(x)


    except ValueError:
        print("Please enter valid type")
        continue

这是我使用方法field_names()add_row()编写的代码版本。
from prettytable import PrettyTable
import random

serviceID = []
services = []
price = []

x = PrettyTable()

x.field_names = ["ServiceID", "Service", "Price"]

while True:
    try:
         ID = random.randint(1,90000) #range high to lower probability of non-uniqueness
         serviceID.append(ID) # in order to store new value if you will need it later

         prompt1 = input("Please add a service name to the list\n")
         services.append(prompt1) # in order to store new value if you will need it later

         prompt2 = input("Please enter a price for the service\n")
         prompt2 == int(prompt2)
         services.append(prompt2) # in order to store new value if you will need it later

         x.add_row([ID, prompt1, prompt2])
         print(x)

    except ValueError:
        print("Please enter valid type")
        continue

谢谢!让我试一下。 - mabishi
有没有一种方法可以访问行中的单个元素,以实现与列表相同的结果?例如,在这种情况下,普通用户将能够输入ServiceID,程序将打印该行的Service和Price数据,并要求确认输入。如果确认,程序将记录条目到(ServiceID、Service和Price)报告中,管理员可以查看。非常感谢你们的帮助! - mabishi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接