我有以下列表:
people = ['John', 'Maurice Smith', 'Sebastian', 'Maurice', 'John Sebastian', 'George', 'George Washington']
您可以注意到,John
,Maurice
,Sebastian
和George
是全名(Maurice Smith
,{{1}的名称或姓氏}和Jogn Sebastian
)。
我想只获得全名。这在python中是否可行?
答案 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 p2
(p
是否为子字符串)
答案 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)