删除列表中的单引号,拆分字符串避免引号 [英] remove single quotes in list, split string avoiding the quotes

查看:89
本文介绍了删除列表中的单引号,拆分字符串避免引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以拆分字符串并避免使用引号(单引号)?

我想从列表中删除单引号(保留列表、字符串和浮点数:

l=['1','2','3','4.5']

所需的输出:

l=[1, 2, 3, 4.5]

下一行既不能用于 int 也不能​​用于 float

l=[float(value) for value in ll]

解决方案

要根据每个值的样子得到 intfloat,所以 '1' 变成 1 并且 "1.2" 变成 1.2,你可以使用 ast.literal_eval 以与 Python 的文字解析器相同的方式进行转换,因此您有一个实际的ints 和 floats 的 list,而不是 strlist (这将包括回显时的引号):

<预><代码>>>>进口AST>>>[ast.literal_eval(x) for x in l][1, 2, 3, 4.5]

与普通的 eval 不同,这不会打开安全漏洞,因为它不能执行任意代码.

您可以使用 map 来稍微提升性能(因为 ast.literal_eval 是用 C 实现的内置函数;通常,map> 获得很少或失去列表推导式),在 Py 2 中,map(ast.literal_eval, l) 或 Py3(其中 map 返回一个生成器,而不是一个 list), list(map(ast.literal_eval, l))

如果目标纯粹是显示不带引号的字符串,您只需手动格式化并完全避免类型转换:

<预><代码>>>>打印('[{}]'.format(', '.join(l)))[1, 2, 3, 4.5]

Is it possible to split a string and to avoid the quotes(single)?

I would like to remove the single quotes from a list(keep the list, strings and floats inside:

l=['1','2','3','4.5']

desired output:

l=[1, 2, 3, 4.5]

next line works neither with int nor float

l=[float(value) for value in ll]

解决方案

To get int or float based on what each value looks like, so '1' becomes 1 and "1.2" becomes 1.2, you can use ast.literal_eval to convert the same way Python's literal parser does, so you have an actual list of ints and floats, rather than a list of str (that would include the quotes when echoed):

>>> import ast
>>> [ast.literal_eval(x) for x in l]
[1, 2, 3, 4.5]

Unlike plain eval, this doesn't open security holes since it can't execute arbitrary code.

You could use map for a mild performance boost here (since ast.literal_eval is a built-in implemented in C; normally, map gains little or loses out to list comprehensions), in Py 2, map(ast.literal_eval, l) or in Py3 (where map returns a generator, not a list), list(map(ast.literal_eval, l))

If the goal is purely to display the strings without quotes, you'd just format manually and avoid type conversions entirely:

>>> print('[{}]'.format(', '.join(l)))
[1, 2, 3, 4.5]

这篇关于删除列表中的单引号,拆分字符串避免引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆