我有一个列表,我想删除双引号内的每一行。
最初是这样的:
[“牛奶,面包,饼干”,“面包,牛奶,饼干,玉米片”]
在修复了我的代码之后,我得到了以下信息:
[例][“牛奶”、“面包”、“饼干”、“面包”、“牛奶”、“饼干”、“玉米片”]
我想要这样的
牛奶,面包,饼干,面包,牛奶,饼干,玉米片]
我尽力了,但我想不出怎么做。
我的代码如下所示:
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发布于 2020-03-10 22:56:51
可以使用“替换”和“列表理解”。
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']]发布于 2020-03-10 23:34:49
试一试,使用列表理解:
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']]https://stackoverflow.com/questions/60626785
复制相似问题