繁体   English   中英

如何在Python中制作基于字符串的多维数组

[英]How to make a string-based multi-dimensional array in Python

我正在练习一些Python,并且在尝试将我以前对多维数组的PHP理解应用于Python数组时遇到错误。

maze_path = [
    [
        "You are in a forest looking into the shrubbery while sitting on a plane. Do you decide to check it out?",
        "yes:Walking in.." = [

        ],
        "no:END_GAME" = []
    ]
]

这是我要设置的数组,具有多个分辨率的数组可以根据传递给迭代器的一组指令进行迭代以移至下一个区域。

我试图执行我的代码,并遇到以下错误(试图查看语法是否合法):

文件“ menu.py”,第159行“是:正在传入..”:[^ SyntaxError:语法无效

我尝试将=符号更改为:== (比较,可以正常工作,但没有达到我的预期...)什么也没做。

我打算这样做的是在数组的第一层进行迭代,如下所示:

for instruction, resolution in maze_path:
  #// do some stuff with each of these informatants
  manage( instruction, resolution, maze_path )

然后,我将找出与遍历数组有关的其他问题。

主要问题 :我可以在Python中制作基于字符串的多维数组吗?

使用dict结构。 您可以使用.items()访问一组( keyvalue )元组,并在这些对之间进行迭代:

maze_path = {
    "You are in a forest looking into the shrubbery while sitting on a plane. Do you decide to check it out?":
    {"yes": "Walking in..",
     "no": "END_GAME" 
    }
}

def manage(i, r):
    print("     You chose {}, this happens: {}".format(i, r))

for description, options in maze_path.items():
    print(description)
    for instruction, resolution in options.items():
        manage(instruction, resolution)

输出:

You are in a forest looking into the shrubbery while sitting on a plane. Do you decide to check it out?
     You chose yes, this happens: Walking in..
     You chose no, this happens: END_GAME

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM