首页 > 解决方案 > 从python中的列表元素列表中删除双引号

问题描述

我有一个列表列表,我想从每行中删除双引号。

最初是这样的:

[['"牛奶、面包、饼干"']、['"面包、牛奶、饼干、玉米饼"']]

修复我的代码后,我得到了这个:

[['“牛奶”、“面包”、“饼干”']、['“面包”、“牛奶”、“饼干”、“玉米饼”']]

我想拥有这样的

[['牛奶','面包','饼干'],['面包','牛奶','饼干','玉米饼']]

我尽力了,但我不知道该怎么做。

我的代码如下所示:

def getFeatureData(featureFile):
x=[]
dFile = open(featureFile, 'r')
for line in dFile:
    row = line.split()
    #row[-1]=row[-1].strip()
    x.append(row)
dFile.close()
print(x)
return x

标签: python

解决方案


您可以使用替换和列表理解。

list_with_quotes = [['"MILK,BREAD,BISCUIT"'], ['"BREAD,MILK,BISCUIT,CORNFLAKES"']]
list_without_quotes = [[l[0].replace('"','')] for l in list_with_quotes]
print(list_without_quotes)
>>out
>>[['MILK,BREAD,BISCUIT'], ['BREAD,MILK,BISCUIT,CORNFLAKES']]

编辑对不起,我很快就做到了,没有注意到我的输出不是你想要的。下面是一个完成这项工作的 for 循环:

list_without_quotes = []
for l in list_with_quotes:
    # get list
    with_quotes = l[0]
    # separate words by adding spaces before and after comma to use split
    separated_words = with_quotes.replace(","," ")
    # remove quotes in each word and recreate list
    words = [ w.replace('"','') for w in separated_words.split()]
    # append list to final list
    list_without_quotes.append(words)
print(list_without_quotes)
>>out
>>[['MILK', 'BREAD', 'BISCUIT'], ['BREAD', 'MILK', 'BISCUIT', 'CORNFLAKES']]

推荐阅读