发布于2019-09-11 11:12 阅读(1113) 评论(0) 点赞(8) 收藏(0)
在Python 2.7中的新功能文档中,它表示对集合文字的支持是从Python 3.1反向移植的。但是,似乎这种支持没有扩展到ast
模块的literal_eval()
功能,如下所示。
这是故意的,疏忽的还是其他的 - 从字符串表示创建文字集的最简洁的解决方法是什么?(我假设以下工作在Python 3.1+中,对吧?)
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
PS我能想到的唯一解决方法就是使用eval()
。
我一直用它来转换pandas DataFrame中的列(df[col] = df[col].apply(to_set)
。对于发现这个问题的人来说可能会有用。它可能不会那么快但它避免使用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))
作者:黑洞官方问答小能手
链接:https://www.pythonheidong.com/blog/article/106878/8243ab4d8dbedc7b737e/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!