如何将“字符串列表"变成真正的列表?
问题描述:
我正在打开一个 .txt
文件,并且必须将其中的列表用于我正在编写的函数.这是文本文件中给出的列表之一:
I am opening a .txt
file and have to use a list inside of it for a function I am writing. This is one of the lists given in the text file:
'[24, 72, 95, 100, 59, 80, 87]\n'
使用 .strip()
去掉 \n
,所以变成:
Using .strip()
it gets rid of the \n
, so it becomes:
'[24, 72, 95, 100, 59, 80, 87]'
我认为使用 split 没有用,因为使用 split(' ')
会产生:
I think using split would be useless, because using split(' ')
would yield:
['[24, 72, 95, 100, 59, 80, 87]']
我认为这只会加深复杂性.将这个字符串列表"转换为我可以使用 for 循环的真实列表的有效方法是什么?我已经尝试了几个小时了,但无法弄清楚.
Which I think just deepens the complications. What is an effective way to turn this 'string list' into a real list I could use a for loop with? I've been trying for a few hours already, and can't figure it out.
答
您可以使用 ast.literal_eval
:
In [8]: strs='[24, 72, 95, 100, 59, 80, 87]\n'
In [9]: from ast import literal_eval
In [10]: literal_eval(strs)
Out[10]: [24, 72, 95, 100, 59, 80, 87]
ast.literal_eval
的帮助:
In [11]: literal_eval?
Type: function
String Form:<function literal_eval at 0xb6eaf6bc>
File: /usr/lib/python2.7/ast.py
Definition: literal_eval(node_or_string)
Docstring:
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.