A multi level nested list
我正在尝试实现一个定制的自动机,其中转换表如下所示:
该表是动态的,即每个单元格的列标题、行名称和数据都可以在运行时确定。列名和行名也是必需的。
我试过这个密码
1 2 3 4 | 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或B:2等中的2个项目,然后我尝试
1 2 3 4 5 6 7 8 | 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),但是我丢失了四个下标。特别是当我事先不知道清单的深度时。需要一些帮助才能以某种简单的方式完成。作为一个新手,我会感谢一些对Python密码的解释。
更新:这是非确定性有限自动机。我试过自动化软件包,但它们没有解决我的问题。根据Tadhg McDonald Jensen的解决方案,它给出了表中第一行(a)的正确输出,但第二行(b)的错误消息。这是密码
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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' |
输出是
1 2 3 4 5 6 7 8 | 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 2 3 4 | 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}} |
然后,
或者,要循环整个表,可以使用3个嵌套for循环:
1 2 3 4 5 6 7 8 | #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) |
老实说,我不明白表代表什么,所以我不能给你具体的建议,但我认为这至少是一个更清晰的数据结构。