python - Python PrettyTable - 在列中输入一次值并更新其出现次数
问题描述
我创建了一个漂亮的表格,如下所示:
from prettytable import PrettyTable
from datetime import datetime, timedelta, timezone
# objects
my_table = PrettyTable()
my_table.field_names = ["Permit_Type", "Count"]
permit_type_list = ["P1", "R4", "P1", "R2", "Q6", "Q6"]
def get_list_of_permissions():
start_count = 0
for permission in permit_type_list:
start_count += 1
my_table.add_row([permission, start_count])
print(my_table)
get_list_of_permissions()
我想要一个提供以下输出的表:
+--------------------------------------+-----------+
| Permit_Type | Count |
+--------------------------------------+-----------+
| P1 | 2 |
| R4 | 1 |
| R2 | 1 |
| Q6 | 2 |
目前,如果 Permit_Type 在列表中出现不止一次,我的代码会在表中多次列出 Permit_Type 并且 Count 只会增加
解决方案
我能够自己解决这个问题:-)
from collections import Counter
from prettytable import PrettyTable
# objects
my_table = PrettyTable()
my_table.field_names = ["Permit_Type", "Count"]
def get_list_of_permissions():
requests = []
for permission in permit_type_list:
requests_in_list.append(permission)
req_count = Counter(requests_in_list)
for key, value in req_count.most_common():
my_table.add_row([key, value])
print(my_table)
推荐阅读
- ios - Swift 单元测试:检查同一类的两个对象是否相等
- python-3.x - 将 csv 文件读取到 jupyter 时忽略索引
- c# - 在 asp.net 核心中使用 VerifyHashedPassword 时出现 NullReferenceException
- java - Ant 构建和 Eclipse 构建不同的结果
- c++ - Windows/C++ -- 将图标渲染为具有透明度的位图
- google-apps-script - 使用 Selection 的 RangeElements 获取 Google Doc 中的所有嵌套文本元素
- javascript - 将上下文信息绑定到 GraphQL 类型?
- permissions - 使用无服务器框架对 lambda 函数的 Cognito 权限
- c++ - 将指针设置为 null 会产生运行时错误
- python-3.x - 如何获取文章的:作者、上传和更新日期?