将变量字符串转换为数组2d

时间:2013-12-17 03:28:13

标签: python-2.7

这是一个字符串。

a = "{'id':'1','nama':'try','stok':'try','satuan':'try'},{'id':'2','nama':'asep','stok':'23','satuan':'pcs'}"

如何将其转换为2D数组?

1 个答案:

答案 0 :(得分:0)

这个字符串形式非常类似于编码的json字符串,通过少量更改,您可以通过json库加载它,用于将此值转换为2D数组的python代码如下:

import json
a = "{'id':'1','nama':'try','stok':'try','satuan':'try'},{'id':'2','nama':'a
sep','stok':'23','satuan':'pcs'}"
res = json.loads("[" + a.replace("'", '"') + "]" )
out = []
for row in res:
    out.append([])
    for cell in row:
        out[-1].append( row[cell] )
print "\noutput: " + str( out )

output: [[u'try', u'1', u'try', u'try'], [u'asep', u'2', u'pcs', u'23']]

在输出上你可以看到不稳定位置的值你可以通过改变内部for语句来确定值的位置。

import json
a = "{'id':'1','nama':'try','stok':'try','satuan':'try'},{'id':'2','nama':'a
sep','stok':'23','satuan':'pcs'}"
res = json.loads("[" + a.replace("'", '"') + "]" )
out = []
for row in res:
    out.append([])
    for cell in [ "id", "nama", "stok", "satuan" ]:
        out[-1].append( row[cell] )
print "\noutput: " + str( out )

output: [[u'1', u'try', u'try', u'try'], [u'2', u'asep', u'23', u'pcs']]
祝你好运