Python:打印以相同字母开头和结尾的所有名称

时间:2015-10-05 17:33:00

标签: python arrays regex

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

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

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

Greg McGuiness
Chloe Nelson
Chiara Samos

我一直在玩正则表达式,但似乎无法正确使用。

5 个答案:

答案 0 :(得分:4)

你可以在没有正则表达式的情况下做到这一点:

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

答案 1 :(得分:2)

为何选择正则表达式?这是一个可怕的"一个班轮"。

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']

答案 2 :(得分:2)

你不需要正则表达式

for employee in employees:
    for name in employee.split(" "):
        if name[0].lower() == name[len(name)-1].lower():
            print(employee)

答案 3 :(得分:2)

我将提供正则表达式的解决方案。

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)]

答案 4 :(得分:1)

为了真正的功能性衬垫:)

In [5]:
filter(lambda e: any(x[0].lower() == x[-1].lower() for x in e.split()), employees)
​
Out[5]:
['Greg McGuiness', 'Chloe Nelson', 'Chiara Samos']

或更具可读性:

filter(
  lambda e: any(x[0].lower() == x[-1].lower() 
                for x in e.split()), 
  employees)

虽然不是RE ......