Python初学者问题:
有没有办法将'[a, b, c]'
形式的字符串直接转换成列表?
就像在type(f('[a, b, c]')) is list == True
/isinstance(f('[a, b, c]'), list) is True
中的一些方法或函数f
一样吗?请注意,最终的列表应该将元素作为单独的字符串,即f('[a, b, c]') returns ['a', 'b', 'c']
我已经检查过this和this了。ast.literal_eval()
失败,并显示错误:
ValueError: malformed string
我的输入列表(字符串)没有标记为unicode,条目也不是单独的string
或int
。
这种转换有没有内置的工具?这本质上是一个“形式”问题。我正在尝试理解是否有一种pythonic
方法可以做到这一点,而不是编写一个较长的函数,使用拆分字符串和转换。
如果您有真知灼见,我们将非常感激。
发布于 2014-07-02 18:40:06
试试这个:
s = '[a ,b, c]'
s = s.replace(" ", "")
l = s[1:-1].split(',')
发布于 2014-07-02 19:08:16
我知道OP明确要求一个非列表理解的解决方案,然而,对于那些可能对涉及列表理解的解决方案感兴趣的人,我留下了这个代码:
>>> s = "[a, 1, b]"
>>> s = [int(i) if i.strip().isdigit() else i.strip() for i in s[1:-1].split(",")]
>>> print(s)
['a', 1, 'b']
它还考虑了元素的类型,into被转换为int
。
发布于 2014-07-02 18:37:49
使用literal_eval
,这将使int保持为int并存留子列表。
In [7]: import re
In [8]: d='[a, b, c, 4, 5, 6,[1,4]]'
In [9]: from ast import literal_eval
In [10]: lit = literal_eval(re.sub('([A-Za-z])', r'"\1"', d))
In [11]: lit[6]
Out[11]: [1, 4]
In [12]: type(lit[6])
Out[12]: list
In [13]: lit
Out[13]: ['a', 'b', 'c', 4, 5, 6, [1, 4]]
如果你想混合数字和字母,你还需要把所有的整型转换成字符串。
您还可以添加到模式中以查找包括@
和.
在内的字符串
In [16]: d='[a, ba, c, 4, 5, 6,[1,4],me@you.com]'
In [17]: lit = literal_eval(re.sub('([A-Za-z@.])', r'"\1"', d))
In [18]: lit
Out[18]: ['a', 'ba', 'c', 4, 5, 6, [1, 4], 'me@you.com']
https://stackoverflow.com/questions/24528464
复制相似问题