Python 2.7 应用regexp并查找列表中的最大数字
我有一张不同名字的名单。我有一个脚本,可以打印出名单上的名字Python 2.7 应用regexp并查找列表中的最大数字,python-2.7,Python 2.7,我有一张不同名字的名单。我有一个脚本,可以打印出名单上的名字 req=urllib2.Request('http://some.api.com/') req.add_header('AUTHORIZATION', 'Token token=hash') response = urllib2.urlopen(req).read() json_content = json.loads(response) for name in json_content: print name['name']
req=urllib2.Request('http://some.api.com/')
req.add_header('AUTHORIZATION', 'Token token=hash')
response = urllib2.urlopen(req).read()
json_content = json.loads(response)
for name in json_content:
print name['name']
输出:
Thomas001
Thomas002
Alice001
Ben001
Thomas120
我需要找到名字托马斯的最大号码。是否有一种简单的方法可以将regexp应用于包含“Thomas”的所有元素,然后将max(list)应用于它们?我想到的唯一方法是遍历列表中的每个元素,将regexp与Thomas匹配,然后去掉字母并将剩余的数字放入一个新列表中,但这似乎相当庞大。您不需要使用regex。只需将结果存储在一个列表中,然后对其应用
sorted
函数即可
>>> l = ['Thomas001',
'homas002',
'Alice001',
'Ben001',
'Thomas120']
>>> [i for i in sorted(l) if i.startswith('Thomas')][-1]
'Thomas120'
您不需要正则表达式,也不需要排序。正如您所说,
max()
很好。为了安全起见,如果列表中包含“Thomasson123”等名称,您可以使用:
names = ((x['name'][:6], x['name'][6:]) for x in json_content)
max(int(b) for a, b in names if a == 'Thomas' and b.isdigit())
第一个赋值创建了一个生成器表达式,因此只有一次遍历序列才能找到最大值。干杯,我想我会解决这个问题的。虽然如果我应用你的解决方案,它会打印出“9”,即使以“Thomas”开头的最大数字远远超过100。@Sarunamberis我假设数字是零填充的。在取最大值之前将字符串强制转换为int将修复它,请参阅更新的答案。