简体   繁体   English

如何使用python将字符串[[]]转换为数组

[英]how to convert string like '[ ]' to array using python

In my data frame,one of column has string values as array look.I get them and stored in an array.Then array look like, 在我的数据框中,其中一列具有字符串值作为数组外观。我将它们获取并存储在数组中。然后数组看起来像,

S=['[18831]', '[12329]', '[4526, 5101, 11276]', '[14388, 14389]'] 

I want it to be 我希望它成为

S= [18831,12329,[4526, 5101, 11276],[14388, 14389]] 

as 2d array to access this IDs.How to do this using python 作为2d数组来访问此ID。如何使用python做到这一点

Those lists are in JSON format so you could use the built in JSON parser. 这些列表采用JSON格式,因此您可以使用内置的JSON解析器。

import json
stringArray = "[1,2,3]"
integerArray = json.loads(stringArray) # [1,2,3]

Check out https://docs.python.org/2/library/json.html 查看https://docs.python.org/2/library/json.html

尝试这个:

[eval(a)[0] if len(eval(a)) == 1 else eval(a) for a in S]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM