删除列表中所有元素,这些元素是python中列表中其他元素的子字符串

时间:2014-09-01 04:41:50

标签: python string substring

我有以下列表:

people = ['John', 'Maurice Smith', 'Sebastian', 'Maurice', 'John Sebastian', 'George', 'George Washington']

您可以注意到,JohnMauriceSebastianGeorge是全名(Maurice Smith,{{1}的名称或姓氏}和Jogn Sebastian)。

我想只获得全名。这在python中是否可行?

2 个答案:

答案 0 :(得分:3)

您可以使用此列表理解删除它们:

[p for p in people if not any(p in p2 for p2 in people if p != p2)]

这会迭代每个人p,然后检查条件:

not any(p in p2 for p2 in people if p != p2)

此内部循环遍历每个人p2(跳过与p相同的情况),并检查p in p2p是否为子字符串)

答案 1 :(得分:0)

# make set of first names from full names
firstnames = set(name.split[0] for name in people if " " in name)

# get names that aren't in the above set
people[:] = (name for name in people if name not in firstnames)