>>> import ast>>> x = '[ "A","B","C" , " D"]'>>> x = ast.literal_eval(x)>>> x['A', 'B', 'C', ' D']>>> x = [n.strip() for n in x]>>> x['A', 'B', 'C', 'D']
def parse_strlist(sl):import reclean = re.sub("[\[\],\s]","",sl)splitted = re.split("[\'\"]",clean)values_only = [s for s in splitted if s != '']return values_only
l_x = [i.strip() for i in x[1:-1].replace('"',"").split(',')]
补充说明
x = '[ "A","B","C" , " D"]'# String indexing to eliminate the brackets.# Replace, as split will otherwise retain the quotes in the returned list# Split to convert to a listl_x = x[1:-1].replace('"',"").split(',')
产出:
for i in range(0, len(l_x)):print(l_x[i])# vvvv output vvvvv'''ABCD'''print(type(l_x)) # out: class 'list'print(len(l_x)) # out: 4
您可以根据需要使用列表理解来解析和清理此列表。
l_x = [i.strip() for i in l_x] # list comprehension to clean upfor i in range(0, len(l_x)):print(l_x[i])# vvvvv output vvvvv'''ABCD'''
x = '[ "A","B","C" , " D", ["E","F","G"]]'l_x = x[1:-1].split(',')l_x = [i.replace(']', '').replace('[', '').replace('"', '').strip() for i in l_x]# returns ['A', 'B', 'C', 'D', 'E', 'F', 'G']
如果你需要保留嵌套列表,它会变得有点难看,但它仍然可以用正则表达式和列表理解来完成:
import re
x = '[ "A","B","C" , " D", "["E","F","G"]","Z", "Y", "["H","I","J"]", "K", "L"]'# Clean it up so the regular expression is simplerx = x.replace('"', '').replace(' ', '')# Look ahead for the bracketed text that signifies nested listl_x = re.split(r',(?=\[[A-Za-z0-9\',]+\])|(?<=\]),', x[1:-1])print(l_x)# Flatten and split the non nested list itemsl_x0 = [item for items in l_x for item in items.split(',') if not '[' in items]# Convert the nested lists to listsl_x1 = [i[1:-1].split(',') for i in l_x if '[' in i]# Add the two listsl_x = l_x0 + l_x1