2024-10-03 02:47:37 发布
网友
我的代码如下
for i in re.finditer('someinteger(.+?)withanother(.+?)', html): x = i.group(1) y = i.group(2)
这里x和y相互关联。如果我想在数组中索引它们,然后根据x对索引进行排序,我该怎么做。考虑到索引长度只有4或5。意思是(i)最多循环4-5次。你知道吗
一个快速代码会有帮助。多数组没有线索。你知道吗
您可以首先将值检索到列表中。re.findall()将自动执行此操作:
re.findall()
values = re.findall(r'someinteger(.+?)withanother(.+?)', html)
然后可以对列表进行排序:
values.sort()
如果您想按x排序(在您的示例中)。你知道吗
x
例如:
>>> s = "someinteger5withanother1someinteger4withanother2someinteger3withanother3" >>> values = re.findall(r'someinteger(.+?)withanother(.+?)', s) >>> values [('5', '1'), ('4', '2'), ('3', '3')] >>> values.sort() >>> values [('3', '3'), ('4', '2'), ('5', '1')]
当然,您仍然在处理字符串,如果您想按数字排序,您需要
values = [(int(x), int(y)) for x,y in values]
将它们全部转换为整数,或者
values.sort(key=lambda x: int(x[0]))
您可以首先将值检索到列表中。
re.findall()
将自动执行此操作:然后可以对列表进行排序:
如果您想按
x
排序(在您的示例中)。你知道吗例如:
当然,您仍然在处理字符串,如果您想按数字排序,您需要
将它们全部转换为整数,或者
相关问题 更多 >
编程相关推荐