我想从字符串列表中删除重复的子字符串。*假设每个列表的重复子字符串是不同的
的例子:
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']
可能有其他方法可以做到这一点,但下面这个方法可以很好地达到目的
那么,你的清单如下:
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)
输出:['Apple', 'Orange', 'Grapes']
对
这是问题的解决方案:
final_lst = [s.replace('State your favorite fruit: ') for s in lst]
使用列表推导式:
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']
你可以在":"获取最后一个索引,如下所示:
[x.split(":")[-1] for x in lst]
您可以遍历列表,然后从每个字符串中取出最后一个单词:
final_lst = [w.split(" ")[-1] for w in lst]