且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除列表中的单引号,拆分字符串避免引号

更新时间:2023-02-21 12:47:27

要根据每个值的样子得到 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]