如何在python中添加和排序多维数组?

2024-10-03 02:47:37 发布

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

我的代码如下

for i in re.finditer('someinteger(.+?)withanother(.+?)', html):
    x = i.group(1)
    y = i.group(2)

这里x和y相互关联。如果我想在数组中索引它们,然后根据x对索引进行排序,我该怎么做。考虑到索引长度只有4或5。意思是(i)最多循环4-5次。你知道吗

一个快速代码会有帮助。多数组没有线索。你知道吗


Tags: 代码inrefor排序htmlgroup数组
1条回答
网友
1楼 · 发布于 2024-10-03 02:47:37

您可以首先将值检索到列表中。re.findall()将自动执行此操作:

values = re.findall(r'someinteger(.+?)withanother(.+?)', html)

然后可以对列表进行排序:

values.sort()

如果您想按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]))

相关问题 更多 >