且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将列表转换为python中的特定json

更新时间:2023-01-17 19:53:28

我假设您的输入列表实际上是一个字符串列表,但如果不是,则表示可以先分割字符串:

I'm assuming your input list is actually a list of strings, but if it's not, you can split the string first:

import re
# If the input data is a list that has one entry, peel it off
input_data = input_data[0]
# Now we should have a string to split...
input_data = re.split(r',\s*', input_data)

对于分组和整理操作,通常使用 collections.defaultdict (以及在这种特殊的求和情况下, collections.Counter 也是如此)

As usual for a group-and-collate operation, collections.defaultdict (and in this particular summing case, collections.Counter too) come in handy:

import collections

input_data = [
    "21:15-21:30 IllegalAgrumentsException 1",
    "21:15-21:30 NullPointerException 2",
    "22:00-22:15 UserNotFoundException 1",
    "22:15-22:30 NullPointerException 1",
]

output = collections.defaultdict(collections.Counter)
for line in input_data:
    time, error, count = line.split(None, 2)
    output[time][error] += int(count)

response = [
    {
        "time": time,
        "logs": [
            {"exception": exception, "count": count}
            for (exception, count) in counter.items()
        ],
    }
    for (time, counter) in output.items()
]

print(response)

输出(格式化的)

[
    {
        "time": "21:15-21:30",
        "logs": [
            {
                "exception": "IllegalAgrumentsException",
                "count": 1,
            },
            {
                "exception": "NullPointerException",
                "count": 2,
            },
        ],
    },
    {
        "time": "22:00-22:15",
        "logs": [
            {
                "exception": "UserNotFoundException",
                "count": 1,
            }
        ],
    },
    {
        "time": "22:15-22:30",
        "logs": [
            {
                "exception": "NullPointerException",
                "count": 1,
            }
        ],
    },
]