Python PrettyTable - 在列中输入一次值并更新其出现次数

Python PrettyTable - enter a value into column once and update count of its occurrences

我创建了一个漂亮的 table 如下:

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()

我想要一个 table 给出以下输出:

+--------------------------------------+-----------+
|             Permit_Type              | Count     |
+--------------------------------------+-----------+
|                 P1                   |     2     |
|                 R4                   |     1     |
|                 R2                   |     1     |
|                 Q6                   |     2     |

目前,我的代码会在 table 中多次列出 Permit_Type 如果它在列表中出现不止一次并且计数只是递增

我自己解决了这个问题:-)

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)