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

juud5qan  于 2023-01-04  发布在  Python
关注(0)|答案(2)|浏览(193)

我有一个列表的列表,我想删除每一行中的双引号。
最初是这样的:
[["牛奶,面包,饼干""],["面包,牛奶,饼干,玉米片""]]
修复我的代码后,我得到了这个:
[['牛奶','面包','饼干'],['面包','牛奶','饼干','玉米片']
我想要这样的
[[牛奶,面包,饼干],[面包,牛奶,饼干,玉米片]]
我尽了最大的努力,但我还是想不出该怎么做。
我的代码如下所示:

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
798qvoo8

798qvoo81#

你可以使用替换和列表解析。

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

xmd2e60i2#

尝试使用列表解析:

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

相关问题