多级嵌套列表

时间:2017-10-24 21:41:23

标签: python nested-lists

我正在尝试实现转换表的自定义自动机:

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代码的一些解释。

更新:这是非确定性有限自动机。我尝试了自动机包,但他们没有解决我的问题。根据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 个答案:

答案 0 :(得分:2)

Pandas非常擅长做表,但你也可以转到字典,无论哪种方式,list都不是你想要的数据结构。

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)

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