繁体   English   中英

如何从字符串列表中删除重复的子字符串?

[英]How do I remove repeating substring from a list of string?

我想从字符串列表中删除重复的子字符串。 *假设每个列表的重复子串不同。

例子:

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) 

输出:['苹果','橙色','葡萄']

问候

这是所问问题的解决方案:

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM