我的电子邮件地址的格式如下列表:排序使用正则表达式的列表在Python
name###@email.com
但数量并不总是存在。例如:[email protected],[email protected] [email protected]等。我想按这些数字排序这些名称,而没有数字的则先排列。我已经提出了一些可行的方法,但是对于Python来说是新手,我很好奇它是否有更好的方法。这里是我的解决方案:
import re
def sortKey(name):
m = re.search(r'(\d+)@', name)
return int(m.expand(r'\1')) if m is not None else 0
names = [ ... a list of emails ... ]
for name in sorted(names, key = sortKey):
print name
这是我的脚本,我曾经用“SORTKEY”唯一的一次,所以我宁愿它是一个lambda函数,但我不知道该怎么做。我知道这将工作:
for name in sorted(names, key = lambda n: int(re.search(r'(\d+)@', n).expand(r'\1')) if re.search(r'(\d+)@', n) is not None else 0):
print name
但我不认为我应该需要调用re.search两次这样做。在Python中做这件事最优雅的方式是什么?
此代码在Python 3失败! –