Python:打印所有以sam开头和结尾的名称

2024-05-15 00:38:04 发布

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

我有一个python雇员姓名数组,如下所示:

employees=["Greg McGuiness", "Lola White", "Richard Bright", "Chloe Nelson", "Bradley Long", "Chiara Samos"]

我需要打印出名字或姓氏以同一字母开头和结尾的所有姓名,在我的示例中,它应该打印这些姓名:

^{pr2}$

我一直在玩弄正则表达式,但似乎无法正确处理。在


Tags: richard数组long姓名whitebright雇员lola
3条回答

您可以不使用正则表达式:

for i in employees:
    for name in i.split(' '):
        if name.lower().endswith(name[0].lower()):
            print i
            break

为什么是regex?这是一个可怕的“一条线”。在

from itertools import izip

employees=["Greg McGuiness", "Lola White", "Richard Bright", "Chloe Nelson", "Bradley Long", "Chiara Samos"]

print([
    n for n, (f, l) in izip(employees, (e.split(' ') for e in employees))
    if f[0].lower() == f[-1].lower()
    or l[0].lower() == l[-1].lower()
])
['Greg McGuiness', 'Chloe Nelson', 'Chiara Samos']

我会用regex给出一个解决方案。在

import re
employees=["Greg McGuiness", "Lola White", "Richard Bright", "Chloe Nelson", "Bradley Long", "Chiara Samos"]
print [i for i in employees if re.findall(r"\b(\w)\w*\1\b",i,re.I)]

相关问题 更多 >

    热门问题