簡體   English   中英

從python中的列表元素列表中刪除雙引號

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM