在python中删除列表中作为列表其他元素的子字符串的所有元素

2024-04-19 04:04:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下清单:

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

您可以注意到,JohnMauriceSebastianGeorge是全名(Maurice SmithJogn SebastianGeorge Washington)的姓名或姓氏。你知道吗

我只想知道全名。这在python中是可能的吗?你知道吗


Tags: johnpeoplesebastian姓名smith姓氏georgemaurice
2条回答
# 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)

您可以使用以下列表删除它们:

[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 p2(是否p是一个子串)。你知道吗

相关问题 更多 >