remove single quotes in list, split string avoiding the quotes

心不动则不痛 提交于 2019-12-23 06:09:58

问题


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]

回答1:


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]



回答2:


The quotes are not part of the strings in your list, so it is not possible to remove them. The output is displaying quotes around the elements of your list to indicate that you are dealing with strings.

You can convert all items in your list ['1','2','3','4.5'] to floats with

>>> l = ['1','2','3','4.5']
>>> [float(x) for x in l]
[1.0, 2.0, 3.0, 4.5]

or

>>> map(float, l)
[1.0, 2.0, 3.0, 4.5]

However, this is not "removing the quotes" from the items of your list, it is converting your list of strings to a list of floats. When printed, the floats are not displayed with quotes around them because they are not strings.




回答3:


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

print([int(i) if float(i) % 1 == 0 else float(i) for i in l])

>>> [1, 2, 3, 4, 4.5]



回答4:


The reason your next line doesn't work is because you have an ll instead of an l



来源:https://stackoverflow.com/questions/35302724/remove-single-quotes-in-list-split-string-avoiding-the-quotes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!