将逗号分隔的数值拆分为子节点。

huangapple go评论55阅读模式
英文:

Break down comma separated values into children nodes

问题

我有一个列表格式如下

[[2020,
'September',
9,
'12:00',
'1',
28,
'Breaking',
7.0,
'Request Body Type Changed,API Path Removed Without Deprecation,Request Property Removed,Response Property Became Optional,Response Success Status Removed']]


这是我用列表创建的层次结构:
```python
{
  'name': '12:00',
  'children': [
    {
      'name': '1',
      'value': 28,
      'children': [
        {
          'name': 'Breaking',
          'value': 7.0,
          'children': [],
          'hidden_children': [
            {
              'name': 'Request Body Type Changed,API Path Removed Without Deprecation,Request Property Removed,Response Property Became Optional,Response Success Status Removed',
              'value': 7.0,
              'itemStyle': {'color': '#ad213e'},
              'label': {'rotate': 0}
            }
          ],
          'itemStyle': {'color': '#ad213e'}
        }
      ]
    }
  ]
}

但正如你所看到的,我把所有的子节点放在了逗号分隔的格式中。我想把它们作为单独的子节点放在层次结构中。这意味着对于Breaking父节点,不是一个hidden_children节点,而是4个hidden_children节点。

期望的层次结构是:

{
    'name': '12:00',
    'children': [
        {
            'name': '1',
            'value': 28,
            'children': [
                {
                    'name': 'Breaking',
                    'value': 7.0,
                    'children': [],
                    'hidden_children': [
                        {
                            'name': 'Request Body Type Changed',
                            'value': 7.0,
                            'itemStyle': {'color': '#ad213e'},
                            'label': {'rotate': 0}
                        },
                        {
                            'name': 'API Path Removed Without Deprecation',
                            'value': 7.0,
                            'itemStyle': {'color': '#ad213e'},
                            'label': {'rotate': 0}
                        },
                        {
                            'name': 'Request Property Removed',
                            'value': 7.0,
                            'itemStyle': {'color': '#ad213e'},
                            'label': {'rotate': 0}
                        },
                        {
                            'name': 'Response Property Became Optional',
                            'value': 7.0,
                            'itemStyle': {'color': '#ad213e'},
                            'label': {'rotate': 0}
                        },
                        {
                            'name': 'Response Success Status Removed',
                            'value': 7.0,
                            'itemStyle': {'color': '#ad213e'},
                            'label': {'rotate': 0}
                        }
                    ],
                    'itemStyle': {'color': '#ad213e'}
                }
            ]
        }
    ]
}

我不确定如何将字符串拆分成不同的子节点来绘制它们。

这是我创建这个层次结构的代码:

def create_hierarchy(api1):
    # ...
    # (代码未变)
    # ...
    if content:
        if "," in content:
            # ...
            # (代码未变)
            # ...
        else:
            content_node = {'name': content, 'value': count}
            if type1 == 'Breaking':
                content_node['itemStyle'] = {'color': '#ad213e'}
                content_node['label'] = {'rotate': 0}
                type_node['hidden_children'].append(content_node)
            else:
                type_node['children'].append(content_node)
                type_node['itemStyle'] = {'color': '#ad213e'}
    return root['children']
# (代码未变)
# ...
hierarchy1 = create_hierarchy(api1)

这里的api1是我的列表的名称。

是否有人有建议或者想法,我该如何做到这一点?


<details>
<summary>英文:</summary>

I have a list which is of this format:

[[2020,
'September',
9,
'12:00',
'1',
28,
'Breaking',
7.0,
'Request Body Type Changed,API Path Removed Without Deprecation,Request Property Removed,Response Property Became Optional,Response Success Status Removed']]


This is the hierarchy I have created with the list:
          {
            &#39;name&#39;: &#39;12:00&#39;,
            &#39;children&#39;: [
              {
                &#39;name&#39;: &#39;1&#39;,
                &#39;value&#39;: 28,
                &#39;children&#39;: [
                  {
                    &#39;name&#39;: &#39;Breaking&#39;,
                    &#39;value&#39;: 7.0,
                    &#39;children&#39;: [
                      
                    ],
                    &#39;hidden_children&#39;: [
                      {
                        &#39;name&#39;: &#39;Request Body Type Changed,API Path Removed Without Deprecation,Request Property Removed,Response Property Became Optional,Response Success Status Removed&#39;,
                        &#39;value&#39;: 7.0,
                        &#39;itemStyle&#39;: {
                          &#39;color&#39;: &#39;#ad213e&#39;
                        },
                        &#39;label&#39;: {
                          &#39;rotate&#39;: 0
                        }
                      }
                    ],
                    &#39;itemStyle&#39;: {
                      &#39;color&#39;: &#39;#ad213e&#39;
                    }
                  }
                ]
              }
            ]
          }

However as you can see I have all the children in a comma separated format. What I want to do this put them as separate children in the hierarchy. Which means instead of one `hidden_children` node for `Breaking` parent node, there will be `4 hidden_children`.




The expected hierarchy is:
{
    &#39;name&#39;: &#39;12:00&#39;,
    &#39;children&#39;: [
        {
            &#39;name&#39;: &#39;1&#39;,
            &#39;value&#39;: 28,
            &#39;children&#39;: [
                {
                    &#39;name&#39;: &#39;Breaking&#39;,
                    &#39;value&#39;: 7.0,
                    &#39;children&#39;: [],
                    &#39;hidden_children&#39;: [
                        {
                            &#39;name&#39;: &#39;Request Body Type Changed&#39;,
                            &#39;value&#39;: 7.0,
                            &#39;itemStyle&#39;: {&#39;color&#39;: &#39;#ad213e&#39;},
                            &#39;label&#39;: {&#39;rotate&#39;: 0}
                        },
                        {
                            &#39;name&#39;: &#39;API Path Removed Without Deprecation&#39;,
                            &#39;value&#39;: 7.0,
                            &#39;itemStyle&#39;: {&#39;color&#39;: &#39;#ad213e&#39;},
                            &#39;label&#39;: {&#39;rotate&#39;: 0}
                        },
                        {
                            &#39;name&#39;: &#39;Request Property Removed&#39;,
                            &#39;value&#39;: 7.0,
                            &#39;itemStyle&#39;: {&#39;color&#39;: &#39;#ad213e&#39;},
                            &#39;label&#39;: {&#39;rotate&#39;: 0}
                        },
                        {
                            &#39;name&#39;: &#39;Response Property Became Optional&#39;,
                            &#39;value&#39;: 7.0,
                            &#39;itemStyle&#39;: {&#39;color&#39;: &#39;#ad213e&#39;},
                            &#39;label&#39;: {&#39;rotate&#39;: 0}
                        },
                        {
                            &#39;name&#39;: &#39;Response Success Status Removed&#39;,
                            &#39;value&#39;: 7.0,
                            &#39;itemStyle&#39;: {&#39;color&#39;: &#39;#ad213e&#39;},
                            &#39;label&#39;: {&#39;rotate&#39;: 0}
                        }
                    ],
                    &#39;itemStyle&#39;: {&#39;color&#39;: &#39;#ad213e&#39;}
                }
            ]
        }
    ]
}

I am not sure how can I split the string to graph them out as different children nodes.

This is my code for creating this hierarchy:

def create_hierarchy(api1):
root = {"name": "root", "children": []}
for row in api1:
year, month, day, time, info_version, api_changes, type1, count, content = row + [None] * (9 - len(row))
year_node = None
for node in root["children"]:
if node["name"] == year:
year_node = node
break
if not year_node:
year_node = {"name": year, "children": []}
root["children"].append(year_node)
month_node = None
for node in year_node["children"]:
if node["name"] == month:
month_node = node
break
if not month_node:
month_node = {"name": month, "children": []}
year_node["children"].append(month_node)
day_node = None
for node in month_node["children"]:
if node["name"] == str(day):
day_node = node
break
if not day_node:
day_node = {"name": str(day), "children": []}
month_node["children"].append(day_node)
hour_node = {"name": str(time), "children": []}
day_node["children"].append(hour_node)
info_node = {"name": info_version, "value": api_changes, "children": []}
hour_node["children"].append(info_node)
if type1:
type_node = None
for node in info_node["children"]:
if node["name"] == type1:
type_node = node
break
if not type_node:
type_node = {"name": type1, "value": count, "children": []}
info_node["children"].append(type_node)
if type1 == "Breaking":
type_node["hidden_children"] = []
type_node["itemStyle"] = {"color": "#ad213e"}
if content:
if "," in content:
content_list = content.split(", ")
for content in content_list:
content_node = {"name": content, "value": count}
if type1 == "Breaking":
content_node["itemStyle"] = {"color": "#ad213e"}
content_node["label"] = {"rotate": 0}
type_node["hidden_children"].append(content_node)
else:
type_node["children"].append(content_node)
type_node["itemStyle"] = {"color": "#ad213e"}
else:
content_node = {"name": content, "value": count}
if type1 == "Breaking":
content_node["itemStyle"] = {"color": "#ad213e"}
content_node["label"] = {"rotate": 0}
type_node["hidden_children"].append(content_node)
else:
type_node["children"].append(content_node)
type_node["itemStyle"] = {"color": "#ad213e"}
return root["children"]

hierarchy1 = create_hierarchy(api1)

`api1` here is the name of my list.

Does anyone have suggestions or ideas how I could do this?



</details>


# 答案1
**得分**: 1

使用列表推导来创建包含逗号分隔字符串中每个元素的字典列表。

通过使用一个变量来保存键(要么是`children`要么是`hidden_children`)来避免所有重复的`if`语句中的重复代码。

```python
if content:
    children_key = "hidden_children" if type1 == "Breaking" else "children"
    content_list = content.split(",")
    type_node[children_key] = [
        {"name": c, "value": count, "itemStyle": {"color": "#ad213e"}, "label": {"rotate": 0}}
        for c in content_list]

无需测试content中是否存在逗号,因为split()会返回一个包含一个字符串的列表,如果逗号不存在,遍历它将返回一个包含一个子项的列表。

英文:

Use a list comprehension to create the list of dictionaries for each element of the comma-separated string.

Avoid all the duplicate code in if statements by using a variable to hold the key, either children or hidden_children.

            if content:
                children_key = &quot;hidden_children&quot; if type1 == &quot;Breaking&quot; else &quot;children&quot;
                content_list = content.split(&quot;,&quot;)
                type_node[children_key] = [
                    {&quot;name&quot;: c, &quot;value&quot;: count, &quot;itemStyle&quot;: {&quot;color&quot;: &quot;#ad213e&quot;}, &quot;label&quot;: {&quot;rotate&quot;: 0}}
                    for c in content_list]
                

There's no need for testing whether comma is in content, because split() will return a list of one string if it doesn't exist, and looping over that will return a list of one child.

huangapple
  • 本文由 发表于 2023年6月2日 07:05:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386224.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定