python - 从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']]
推荐阅读
- python - 为什么 Pandas 的空格分隔符会跳过我的值之一?
- javascript - 如何基于权限进行条件渲染
- html - 您如何使图像准确地跨越 eBay 的描述字段的宽度?(无水平滚动)
- python - 显示图像的文件名 Python imshow
- c++ - 我的 c++ 程序似乎没有评估字符串和我拥有但使用 getline 输入的变量之间的比较
- python-3.x - 我们可以将 python 32 位用于 Microsoft 视觉代码 64 位吗?
- mysql - 使用 django 左连接到最新行
- firebase - 无法在颤动中获取令牌ID
- javascript - 如何从 javascript 数组调用地图功能
- java - 安卓:java.lang.ClassCastException