代码之家  ›  专栏  ›  技术社区  ›  Abrar

多级嵌套列表

  •  0
  • Abrar  · 技术社区  · 8 年前

    我正在尝试实现一个定制的自动机,其中转换表如下所示:

    enter image description here

    我试过这个密码

    table = []
    table.append(["A",[0,["B",2],["C1",2]],[1,["C1",1]]])
    table.append(["B",[0,["C",1]],[1,["C2",1]]])
    table.append(["C",[0,["C1",1]],[1,["C2",1]]])
    

    但我无法从B:2等访问单元格中的单个项目,即B或2。然后我尝试了

    row = ["A","B","C","C1","C2"]
    col = [0,1]
    table = [] 
    table.append([[["B",2],["C1",2]],["C1",1]])
    table.append([["C",1],["C2",1]])
    table.append([["C1",1],["C2",1]])
    
    print(table[0][0][0][0])
    

    现在,我可以访问单个项(在上述情况下为B),但我丢失了四个下标。特别是当我事先不知道清单的深度时。需要一些帮助才能以简单的方式完成。作为一个新手,我将非常感谢对pythonic代码的一些解释。

    更新: 这是非确定性有限自动机。我试过Automation软件包,但他们没有解决我的问题。根据Tadhg-Mcdonald-Jensen的解决方案,它为表中的第一行(A)提供了正确的输出,但为第二行(B)提供了错误消息。这是代码

    table = {}
    table["A"] = {0: {"B":2, "C1":2}, 1: {"C1":1}}
    table["B"] = {0: {"C":1},         1: {"C2",1}}
    table["C"] = {0: {"C1":1},        1: {"C2",1}}
    
    for key,value in table["A"][0].items():  \\ok treated as dictionary (1)
        print(key, value, sep="\t")        
    for key,value in table["A"][1].items():  \\ok treated as dictionary (2)
        print(key, value, sep="\t")          
    for key,value in table["B"][0].items():  \\ok treated as dictionary (3)
        print(key, value, sep="\t")          
    for key,value in table["B"][1].items():  \\wrong: why treated as set? Although same as (2)
        print(key, value, sep="\t")          \\Error message: AttributeError: 'set' object has no attribute 'items' 
    

    输出为

    B   2
    C1  2 
    C1  1
    C   1
    Traceback (most recent call last):
      File "C:/Users/Abrar/Google Drive/Tourism Project/Python Projects/nestedLists.py", line 17, in <module>
    for key,value in table["B"][1].items():
    AttributeError: 'set' object has no attribute 'items'
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Tadhg McDonald-Jensen    8 年前

    Pandas擅长做表格,但你也可以使用字典,不管怎样,列表都不是你想要的数据结构。

    table = {}
    table["A"] = {0: {"B":2, "C1":2}, 1: {"C1":1}}
    table["B"] = {0: {"C":1},         1: {"C2":1}}
    table["C"] = {0: {"C1":1},        1: {"C2":1}}
    

    然后 table["A"][0] 将为您提供第一个元素,每个元素将有一个或多个条目,如果您想迭代这些条目,您可以这样做 for key,value in table["A"][0].items()

    或者,要迭代整个表,可以使用3个嵌套for循环:

    #do_stuff = print
    for row, line in table.items():
        #each row in the table, row will go through ("A", "B", "C")
        for column, cell in line.items():
            #each cell in the row, column will go through (0, 1)
            for label, value in cell.items(): 
                #each entry in cell, most only have one entry except table["A"][0]
                do_stuff(row, column, label, value)
    

    老实说,我不明白这个表代表了什么,所以我不能给你具体的建议,但我认为这至少是一个更清晰的数据结构。