本文介绍了字符串,数字数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从一个节目我产生一串数据,并将其存储在一个文件中。的文件的内容的一个例子是
From one program I generate bunch of data and it is stored in a file. An example of the file's contents is
[[1, 2, 3], [4, 5, 6]]正如你所看到的,数据有一个数组的确切形式。后来在另一个程序我想读取数据,并使用它。我使用
As you can see, the data has the exact form of an array. Later in another program I want to read the data and use it. I am using
text_file = open('DataFile.txt') lines = text_file.readlines() #We have only 1 line but this doesn't matter变量行 1元素的数组是字符串 [1,2,3],[4,5,6 ]] 。我想这个字符串再次数值数组。只是同样的分隔符等等。我怎么能这样做?
The variable lines is an array of 1 element which is the string [[1, 2, 3], [4, 5, 6]]. I want this string to be again a numeric array. Just with the same delimiters etc. How can I do this?
推荐答案您可以使用的 ast.literal_eval :
You can use ast.literal_eval:
>>> from ast import literal_eval >>> mystr = '[[1, 2, 3], [4, 5, 6]]' >>> x = literal_eval(mystr) >>> x [[1, 2, 3], [4, 5, 6]] >>> type(x) <type 'list'> >>>更多推荐
字符串,数字数组
发布评论