python将列表字符串转换为列表列表 [英] python convert string of lists into a list of lists
本文介绍了python将列表字符串转换为列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种将字符串转换为列表列表的优雅方法.我正在从文本文件中读取它们,因此无法更改接收字符串的格式.这里以示例字符串为例:
I am looking for an elegant way to convert a string into a list of lists. I am reading them from a text file so can't alter the format that i receive the string in. Here as an example string:
a = "[[1,2,3],[4,5,6],[7,8,9]]"
我想将其转换为如下形式:
I would like to convert it into something like this:
c = [[1,2,3],[4,5,6],[7,8,9]]
我认为做到这一点的唯一方法是有点笨拙,其中涉及使用.split()和.replace()的几个步骤
The only way I can think to do this is a bit clunky involving several steps using .split() and .replace()
b = a.split('],[')
for i in range(len(b)):
b[i] = b[i].replace('[','')
b[i] = b[i].replace(']','')
b=[[x] for x in b]
b = [float(x[0].split(',')) for x in b]
c=[]
for l in b:
n=[]
for x in l:
n.append(float(x))
c.append(n)
这是可行的,令人反感和笨拙.如果有人知道这样做的优雅方式,请告诉我.非常感谢
whilst this works, its repulsive and clunky. If anyone knows of an elegant way of doing this please let me know. Many thanks
推荐答案
>>> import json
>>> json.loads("[[1,2,3],[4,5,6],[7,8,9]]")
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
这很容易:)
>>> a = "[[1,2,3],[4,5,6],[7,8,9]]"
>>> import ast
>>> m=ast.literal_eval(a)
>>> m
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
这也行得通
这篇关于python将列表字符串转换为列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文