2 回答
TA贡献1982条经验 获得超2个赞
您可以使用替换和列表理解。
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']]
TA贡献2039条经验 获得超7个赞
尝试使用列表理解:
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']]
添加回答
举报