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.
This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.
在您的示例中:
from ast import literal_eval
s = '(1,2,3,4,5),(5,4,3,2,1)'
l = literal_eval(s)
print l
# ((1, 2, 3, 4, 5), (5, 4, 3, 2, 1))
print [(x[0], x[-1]) for x in l]
# [(1, 5), (5, 1)]
>>> s = '(1,2,3,4,5),(5,4,3,2,1)'
>>> ts = eval(s)
>>> ts
((1, 2, 3, 4, 5), (5, 4, 3, 2, 1))
>>> tsp = [(el[0],el[-1]) for el in ts]
>>> tsp
[(1, 5), (5, 1)]
不过,使用eval并不是一个好的做法。
另一个选项是使用re模块解析字符串。
>>> a = re.findall('\([^)]*\)',s)
>>> a
['(1,2,3,4,5)', '(5,4,3,2,1)']
Regexp模式意味着:
\( #opening parenthesis
[^)]* #from 0 to infinite symbols different from )
\) #closing parenthesis
是的。
>>> b = [el.strip('()') for el in a]
>>> b
['1,2,3,4,5', '5,4,3,2,1']
>>> c = [el.split(',') for el in b]
>>> c
[['1', '2', '3', '4', '5'], ['5', '4', '3', '2', '1']]
>>> d = [tuple(int(el2) for el2 in el) for el in c]
>>> d
[(1, 2, 3, 4, 5), (5, 4, 3, 2, 1)]
此外,您还可以执行以下操作:
>>> [tuple(int(i) for i in el.strip('()').split(',')) for el in s.split('),(')]
[(1, 2, 3, 4, 5), (5, 4, 3, 2, 1)]
在这种情况下,
ast
模块可能很有用:因此,
my_tuples
有一个元组与字符串的元组。现在,我们可以使用列表理解获得所有元组的第一个和最后一个元素:您可以使用^{} :
在您的示例中:
您可以使用
eval
。我想这是最短的。不过,使用
eval
并不是一个好的做法。另一个选项是使用
re
模块解析字符串。Regexp模式意味着:
是的。
此外,您还可以执行以下操作:
这种方法根本不需要模块。但是它不是很健壮(如果输入字符串有一些不一致,例如括号和逗号之间的空格
...), (...
,那么noting就可以工作)。相关问题 更多 >
编程相关推荐