从列表创建嵌套树

时间:2018-11-17 10:46:10

标签: python dictionary tree

从列表列表中,我想创建一个嵌套的字典,该字典的键将指向子列表中的下一个值。另外,我想计算一系列子列表值的出现次数。

示例:

从这样的列表列表中:

[['a', 'b', 'c'],
['a', 'c'],
['b']]

我想这样创建一个嵌套字典:

{
  'a': {
          {'b': 
                {
                'c':{}
                'count_a_b_c': 1
                }
            'count_a_b*': 1
          }, 
          {'c': {},
           'count_a_c': 1
          }
          'count_a*': 2
        },
  {
  'b':{},
  'count_b':1
  }
}

请注意,计数键的名称无关紧要无关紧要,它们的名称仅供参考。

1 个答案:

答案 0 :(得分:1)

我很好奇我会怎么做,并提出了这个建议:

protected void GenerateReport(object sender, EventArgs e)
{
    Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
    Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);
    using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
    {
        PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
        Phrase phrase = null;
        PdfPCell cell = null;
        PdfPTable table = null;
        Color color = null;

        document.Open();

        //Header Table
        table = new PdfPTable(2);
        table.TotalWidth = 500f;
        table.LockedWidth = true;
        table.SetWidths(new float[] { 0.3f, 0.7f });


        //Company Name and Address
        phrase = new Phrase();
        phrase.Add(new Chunk(" pdf demo  \n\n", FontFactory.GetFont("Arial", 16, Font.BOLD, Color.RED)));
        phrase.Add(new Chunk("Aurangabad, Maharashtra 431116,\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        phrase.Add(new Chunk("India\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        // phrase.Add(new Chunk("Seattle, USA", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
        cell.VerticalAlignment = PdfCell.ALIGN_TOP;
        table.AddCell(cell);

        //Separater Line
        color = new Color(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
        DrawLine(writer, 25f, document.Top - 79f, document.PageSize.Width - 25f, document.Top - 79f, color);
        DrawLine(writer, 25f, document.Top - 80f, document.PageSize.Width - 25f, document.Top - 80f, color);
        document.Add(table);

        table = new PdfPTable(2);
        table.HorizontalAlignment = Element.ALIGN_LEFT;
        table.SetWidths(new float[] { 0.3f, 1f });
        table.SpacingBefore = 20f;

        //Employee Details
        cell = PhraseCell(new Phrase("Certificate Record", FontFactory.GetFont("Arial", 12, Font.UNDERLINE, Color.BLACK)), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingTop = 30f;
        table.AddCell(cell);
        cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingBottom = 30f;

        table.AddCell(cell);

        ////Photo
        //cell = ImageCell(string.Format("~/photos/{0}.jpg", dr["id"]), 25f, PdfPCell.ALIGN_CENTER);
        //table.AddCell(cell);


        //String tgender = dr["gender"].ToString();
        //String tchild_no = dr["child_no"].ToString();


        phrase = new Phrase();
        phrase.Add(new Chunk("प्रिया", FontFactory.GetFont("Arial", 10, Font.BOLD, Color.BLACK)));
        phrase.Add(new Chunk("name", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)));
        cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
        cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
        table.AddCell(cell);
        document.Add(table);

        //DrawLine(writer, 160f, 80f, 160f, 690f, Color.WHITE);
        //DrawLine(writer, 115f, document.Top - 200f, document.PageSize.Width - 100f, document.Top - 200f, Color.WHITE);

        table = new PdfPTable(2);
        table.SetWidths(new float[] { 0.5f, 2f });
        table.TotalWidth = 340f;
        table.LockedWidth = true;
        table.SpacingBefore = 20f;
        table.HorizontalAlignment = Element.ALIGN_RIGHT;



           //name
        table.AddCell(PhraseCell(new Phrase("Name:", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        table.AddCell(PhraseCell(new Phrase("" + "प्रिया", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingBottom = 10f;
        table.AddCell(cell);


        document.Add(table);
        document.Close();
        byte[] bytes = memoryStream.ToArray();
        memoryStream.Close();
        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=Certificate.pdf");
        Response.ContentType = "application/pdf";
        Response.Buffer = true;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(bytes);
        Response.End();
        Response.Close();
    }
}

private static void DrawLine(PdfWriter writer, float x1, float y1, float x2, float y2, Color color)
{

    PdfContentByte contentByte = writer.DirectContent;
    contentByte.SetColorStroke(color);
    contentByte.MoveTo(x1, y1);
    contentByte.LineTo(x2, y2);
    contentByte.Stroke();
}
private static PdfPCell PhraseCell(Phrase phrase, int align)
{
    PdfPCell cell = new PdfPCell(phrase);
    cell.BorderColor = Color.WHITE;
    cell.VerticalAlignment = PdfCell.ALIGN_TOP;
    cell.HorizontalAlignment = align;
    cell.PaddingBottom = 2f;
    cell.PaddingTop = 0f;
    return cell;
}

private static PdfPCell ImageCell(string path, float scale, int align)
{
    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath(path));
    image.ScalePercent(scale);
    PdfPCell cell = new PdfPCell(image);
    cell.BorderColor = Color.WHITE;
    cell.VerticalAlignment = PdfCell.ALIGN_TOP;
    cell.HorizontalAlignment = align;
    cell.PaddingBottom = 0f;
    cell.PaddingTop = 0f;
    return cell;
}

这里没什么特别的事...

例如:

lst = [['a', 'b', 'c'],
['a', 'c'],
['b']]

tree = {}
for branch in lst:
    count_str = 'count_*'
    last_node = branch[-1]
    cur_tree = tree
    for node in branch:
        if node == last_node:
            count_str = count_str[:-2] + f'_{node}'
        else:
            count_str = count_str[:-2] + f'_{node}_*'
        cur_tree[count_str] = cur_tree.get(count_str, 0) + 1
        cur_tree = cur_tree.setdefault(node, {})

产生:

import json
print(json.dumps(tree, sort_keys=True, indent=4))

它不能完全再现您的想象-但这在一定程度上是由于您期望的结果不是有效的python字典...

但这可能是您解决问题的起点。