¿Cómo usar Pretty Table en Python para imprimir datos de varias listas?

Soy relativamente nuevo en la progtwigción de Python, uso Python 3.x, y estoy trabajando en un sistema POS de Barbería donde el administrador tendrá el privilegio de agregar Servicios y sus precios correspondientes. Estoy usando la biblioteca Pretty Table para imprimir una tabla con serviceID, servicio y precio.

Aquí está mi código:

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 

Cuando ingreso el primer servicio y el precio, la salida es:

 +-----------+---------+--------+ | ServiceID | Service | Price | +-----------+---------+--------+ | [9880] | ['box'] | ['90'] | +-----------+---------+--------+ 

Cuando entro en el segundo servicio y el precio, la salida es la siguiente:

 +---------------+-----------------+--------------+ | ServiceID | Service | Price | +---------------+-----------------+--------------+ | [9880, 47612] | ['box', 'trim'] | ['90', '80'] | +---------------+-----------------+--------------+ 

Me gustaría que la salida fuera esta:

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

¿Alguien sabe como lograr esto? Cualquier ayuda sería apreciada.

Podemos hacerlo agregando una fila al objeto add_row mediante el método add_row .

Demostración :

 >>> 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 | +-----------+---------+-------+ >>> 

Eliminar fila :

Utilice el método del_row() . Necesitamos pasar el índice de la fila que queremos eliminar.

 >>> 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 | +-----------+---------+-------+ 

Necesidad de manejar la excepción si proporcionamos un valor de índice mayor que el total de filas en la excepción boostá, esa necesidad debe manejarse en su código.

La excepción es:

 >>> x.del_row(10) Traceback (most recent call last): File "", line 1, in  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! 

Nota :

  1. Utilice raw_input() para Python 2.x

  2. Use input() para Python 3.x

Lo he logrado siempre creando una nueva instancia de la clase prettytable.PrettyTable dentro del bucle while.

 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 

Aquí está mi versión de código que usa los nombres de campo de los métodos () y 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