python中如何将列表按列打印_如何在Python中使用Pretty Table打印多个列表中的数据?...

我们可以通过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 |

+-----------+---------+-------+

如果我们提供的索引值大于异常中的总行数,则需要处理异常,需要在ur代码中处理.

例外情况是:

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

注意:

>对Python 2.x使用raw_input()>对Python 3.x使用input()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值