问题描述
在 Python 2.7新增功能文档中它说对set文字的支持是从Python 3.1向后移植的.但是,似乎这种支持没有扩展到ast
模块的literal_eval()
功能,如下所示.
In the What’s New in Python 2.7 document it says that support for set literals was back-ported from Python 3.1. However it appears that this support was not extended to the ast
module's literal_eval()
function, as illustrated below.
这是故意的还是疏忽大意的?从字符串表示形式创建文字集的最干净的解决方法是什么? (我假设以下内容在Python 3.1+中有效,对吧?)
Was this intentional, an oversight, or something else -- and what are the cleanest workarounds for creating a literal set from a string representation? (I assume the following works in Python 3.1+, right?)
import ast
a_set = {1,2,3,4,5}
print a_set
print ast.literal_eval('{1,2,3,4,5}')
显示错误消息的输出:
set([1, 2, 3, 4, 5])
Traceback (most recent call last):
File "...\setliterals.py", line 4, in <module>
print ast.literal_eval('{1,2,3,4,5}')
File "...\Python\lib\ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "...\Python\lib\ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string
P.S.我能想到的唯一解决方法是使用eval()
.
P.S. The only workaround I can think of is to use eval()
.
推荐答案
我一直在用它来转换pandas DataFrame(df[col] = df[col].apply(to_set)
中的列.对于发现此问题的任何人可能很有用.它可能不那么快但它避免使用eval
.
I've been using this for converting columns in a pandas DataFrame (df[col] = df[col].apply(to_set)
. Might be useful for anyone finding this question. It may not be as fast but it avoids using eval
.
def to_set(set_str):
"""
Required to get around the lack of support for sets in ast.literal_eval.
It works by converting the string to a list and then to a set.
Parameters
----------
set_str : str
A string representation of a set.
Returns
-------
set
Raises
------
ValueError
"malformed string" if the string does not start with '{' and and end
with '}'.
"""
set_str = set_str.strip()
if not (set_str.startswith('{') and set_str.endswith('}')):
raise ValueError("malformed string")
olds, news = ['{', '}'] , ['[',']']
for old, new in izip(olds, news):
set_str = set_str.replace(old, new)
return set(literal_eval(set_str))
这篇关于ast.literal_eval()是否支持Python 2.7中的设置文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!