简体   繁体   English

从python列表中删除其他引号

[英]Remove additional quotes from python list

I have a list with below pattern and i want to get rid of " which is present at the beginning and end of each sub list. I tried replace, strip but they are not the attribute of list and therefore gives AttributeError . 我有一个具有以下模式的列表,并且我想摆脱每个子列表的开头和结尾处出现的" 。我尝试了替换,剥离,但它们不是列表的属性,因此给出了AttributeError

lst = [["'123', 'Name1', 'Status1'"], ["'234', 'Name2', 'Status2'"]]

I am looking for below as my final result: 我正在寻找以下作为我的最终结果:

lst = [['123', 'Name1', 'Status1'], ['234', 'Name2', 'Status2']]

Please suggest how to remove double quotes from each sub list. 请建议如何从每个子列表中删除双引号。

You can use shlex.split after removing commas with replace : 您可以使用shlex.split删除逗号后replace

import shlex

lst = [["'123', 'Name1', 'Status1'"], ["'234', 'Name2', 'Status2'"]]
r = [shlex.split(x[0].replace(',', '')) for x in lst]
# [['123', 'Name1', 'Status1'], ['234', 'Name2', 'Status2']]

This should do the trick: 这应该可以解决问题:

result = [[element.strip("'") for element in sub_list[0].split(', ')] for sub_list in lst]

I'm assuming that the format for the string is "strings wrapped in single quotes separated by commas and spaces." 我假设字符串的格式是“用单引号引起来的字符串,用逗号和空格分隔。” Note that my code will probably not do the expected thing with input like [["'A comma here, changes the parsing', 'no comma here'"], ...] . 请注意,我的代码可能不会使用[["'A comma here, changes the parsing', 'no comma here'"], ...]类的输入来完成预期的操作。 (This would look to my code like three elements in a list, while I imagine you want to consider it two.) (在我的代码中,这看起来像一个列表中的三个元素,而我想您想将其考虑为两个。)

EDIT 编辑

This is perhaps easier to understand as compared to the longer list comprehension: 与较长的列表理解相比,这也许更容易理解:

result = []
for sub_list in lst:
    s = sub_list[0]
    result.append([element.strip("'") for element in s.split(', ')])

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

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