从python中的列表元素列表中删除双引号

2024-04-25 17:00:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

最初是这样的:

[['"MILK,BREAD,BISCUIT"'], ['"BREAD,MILK,BISCUIT,CORNFLAKES"']]

在修复代码后,我得到了以下信息:

[['"MILK', 'BREAD', 'BISCUIT"'], ['"BREAD', 'MILK', 'BISCUIT', 'CORNFLAKES"']]

我想要这样的

[['MILK', 'BREAD', 'BISCUIT'], ['BREAD', 'MILK', 'BISCUIT', 'CORNFLAKES']]

我尽了最大的努力,但我不知道怎么做

我的代码如下所示:

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

Tags: 代码信息列表deflineopenrowmilk
2条回答

尝试以下方法,使用列表:

initial = [['"MILK,BREAD,BISCUIT"'], ['"BREAD,MILK,BISCUIT,CORNFLAKES"']]

final = [item[0].replace('"', '').split(',') for item in initial]

print(final)

输出:

[['MILK', 'BREAD', 'BISCUIT'], ['BREAD', 'MILK', 'BISCUIT', 'CORNFLAKES']]

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

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']]

相关问题 更多 >