我想從字串串列中洗掉重復的子字串。*假設每個串列的重復子串不同。
例子:
lst = ['State your favorite fruit: Apple', 'State your favorite fruit: Orange', 'State your favorite fruit: Grapes']
期望的結果:
final_lst = ['Apple', 'Orange', 'Grapes']
編輯:對不起,如果我最初的問題不清楚。我希望從每個字串串列中找到唯一的單詞。
lst1 = ['This is a bag', 'This is a cat', 'This is a dog']
lst2 = ['Favorite drink: Cola', 'Favorite drink: Sprite']
lst3 = ['My name is James', 'My name is Mary Jane', 'My name is Lopez']
期望的輸出:
final_lst1 = ['bag', 'cat', 'dog']
final_lst2 = ['Cola', 'Sprite']
final_lst3 = ['James', 'Mary Jane', 'Lopez']
uj5u.com熱心網友回復:
可能還有其他某些方法可以做到這一點,但下面的方法非常適合此目的
所以,你的清單如下:
lst = ['State your favorite fruit: Apple', 'State your favorite fruit: Orange', 'State your favorite fruit: Grapes']
現在,將所有單詞分成一個新串列
seperate_words = (" ".join(lst)).split(" ") #First we join all the sentences of the list
# with a space in between using the "join" method of string.
#Then consequently splitting the list by a space
最后,要獲得唯一的單詞,請使用如下串列理解
unique_words = [word for word in seperate_words if seperate_words.count(word) == 1]
print(unique_words)
輸出:['蘋果','橙色','葡萄']
問候
uj5u.com熱心網友回復:
這是所問問題的解決方案:
final_lst = [s.replace('State your favorite fruit: ') for s in lst]
uj5u.com熱心網友回復:
只需使用串列理解:
lst = ['State your favorite fruit: Apple', 'State your favorite fruit: Orange', 'State your favorite fruit: Grapes']
final_lst = [s.replace('State your favorite fruit: ', '') for s in lst]
print(final_lst)
輸出:
['Apple', 'Cherry', 'Grapes']
uj5u.com熱心網友回復:
您可以拆分“:”并獲得如下所示的最后一個索引:
[x.split(":")[-1] for x in lst]
uj5u.com熱心網友回復:
您可以遍歷串列,然后從每個字串中取出最后一個單詞:
final_lst = [w.split(" ")[-1] for w in lst]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/323933.html
