如何将该字符串转换为列表列表? [英] How can I convert this string to list of lists?

查看:47
本文介绍了如何将该字符串转换为列表列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户键入[[0,0,0], [0,0,1], [1,1,0]]并按Enter, 程序应将此字符串转换为几个列表; 一个包含[0][0][0]的列表,另一个包含[0][0][1]的列表,最后一个包含[1][1][0]

If a user types in [[0,0,0], [0,0,1], [1,1,0]] and press enter, the program should convert this string to several lists; one list holding [0][0][0], other for [0][0][1], and the last list for [1][1][0]

python有一个很好的方法来解决这个问题吗?

Does python have a good way to handle this?

推荐答案

这比Satoru的灵活得多,并且不使用任何库.不过,它不适用于嵌套更深的列表.为此,我认为您将需要一个递归函数(或循环)或eval.

This is a little more flexible than Satoru's, and doesn't use any libraries. Still, it won't work with more deeply nested lists. For that, I think you would need a recursive function (or loop), or eval.

str = "[[0,0,0],[0,0,1],[1,1,0]]"
strs = str.replace('[','').split('],')
lists = [map(int, s.replace(']','').split(',')) for s in strs]

列表现在包含所需列表的列表.

lists now contains the list of lists you want.

这篇关于如何将该字符串转换为列表列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆