将字符串2d列表转换回python中的2d列表 [英] convert a string 2d list back to 2d list in python

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

问题描述

我刚刚开始玩python. 我知道我们可以使用str()将任何列表转换为字符串 喜欢:

I just started playing around with python. I know that we can convert any list to a string using str() Like:

>>> l = [[1,1] , [2,2] , [3,3]]
>>> l
[[1, 1], [2, 2], [3, 3]]
>>> type(l)
<type 'list'>
>>> str(l)
'[[1, 1], [2, 2], [3, 3]]'
>>> list_string = str(l)
>>> list_string
'[[1, 1], [2, 2], [3, 3]]'
>>> type(list_string)
<type 'str'>

有没有一种方法可以将list_string转换回2d列表? 基本上,是否存在将其转换回其原始形式的功能?

Is there a way to convert list_string back to a 2d list ?? Basically, is there a function to convert this back to its original form ?

old_list = magic_conversion_func(list_string)

>>>old_list
[[1, 1], [2, 2], [3, 3]]

我尝试了list(),但是它将字符串中的每个字符转换为一个新的list元素.

I tried list() but that converts every char in the string to a new list element.

>>> list(list_string)
['[', '[', '1', ',', ' ', '1', ']', ',', ' ', '[', '2', ',', ' ', '2', ']', ',', ' ', '[', '3', ',', ' ', '3', ']', ']']

那不是我想要的

推荐答案

使用 ast.literal_eval

>>> list_string = '[[1, 1], [2, 2], [3, 3]]'
>>> import ast
>>> type(ast.literal_eval(list_string))
<type 'list'>

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

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