2024-04-19 04:04:35 发布
网友
我有以下清单:
people = ['John', 'Maurice Smith', 'Sebastian', 'Maurice', 'John Sebastian', 'George', 'George Washington']
您可以注意到,John、Maurice、Sebastian和George是全名(Maurice Smith、Jogn Sebastian和George Washington)的姓名或姓氏。你知道吗
John
Maurice
Sebastian
George
Maurice Smith
Jogn Sebastian
George Washington
我只想知道全名。这在python中是可能的吗?你知道吗
# 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,然后检查条件:
p
not any(p in p2 for p2 in people if p != p2)
这个内部循环迭代每个人p2(跳过与p相同的情况),并检查p in p2(是否p是一个子串)。你知道吗
p2
p in p2
您可以使用以下列表删除它们:
它迭代每个人
p
,然后检查条件:这个内部循环迭代每个人
p2
(跳过与p
相同的情况),并检查p in p2
(是否p
是一个子串)。你知道吗相关问题 更多 >
编程相关推荐