[英]Remove double quotes from list of list elements in 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
您可以使用替换和列表理解。
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']]
试试这个,使用列表理解:
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']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.