开发者

How do I convert string version of an array into an actual array?

s = "[[A, B],[E,R], [E,G]]"

Is ther开发者_开发知识库e a built-in way to convert this string into an array? (s[][])


There is, but in your case it will assume A B E R G to be variables, is this the case?
If this is not the case you will need to do some extra formatting with the string.

This will work if the variables A B E R G are set:
s = eval(s)

If the letters need to be strings you will have to do some kind of regexp to replace all occurrences of chars with quoted chars.


If A B E R G are not variables but just a string then you can use the following code:

tmp = ''
for c in s:
   if c.isalpha():
      t+="'%s'"%c
   else:
      t+=c
eval(t) # will give you [['A', 'B'], ['E', 'R'], ['E', 'G']]

OR:(very ugly i know but don't beat me too much - just experementing)

evel(''.join(map(lambda x: s[x[0]] if not s[x[0]].isalpha() else "'%s'" % s[x[0]], enumerate(map(lambda c: c.isalpha(), s)))))


If you can slightly modify the string, you could use the JSON module to convert the string into list.

>>> import json

>>> s = '[["A", "B"], ["E", "R"], ["E", "G"]]'
>>> array = json.loads(s)
>>> array
[[u'A', u'B'], [u'E', u'R'], [u'E', u'G']]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜