首页 > 解决方案 > 如何按方括号之间的内容进行数字排序

问题描述

我有以下场景,其中文本文件具有以下输出:

DecodingIndex[ 1]   PresentationIndex[ 2]
DecodingIndex[ 2]   PresentationIndex[ 3]
DecodingIndex[ 3]   PresentationIndex[ 1]
etc...

由于它按顺序显示 DecodingIndex 中的数字,因此我希望它按 PresentationIndex 排序。如下所示:

DecodingIndex[ 3]   PresentationIndex[ 1]
DecodingIndex[ 1]   PresentationIndex[ 2]
DecodingIndex[ 2]   PresentationIndex[ 3]

有没有一种简单的方法可以在 Python 中做到这一点?这些数字一直达到数万。方括号之间的距离对于小于 10 的数字总是有间隙,然后拥抱数字,例如 DecodingIndex[32100]

希望这是有道理的,并感谢您的帮助!

=======

这是我尝试过的:1)我遍历文件中的每一行并存储到一个行[]列表中2)遍历行[]列表中的每个项目,同时使用以下正则表达式模式re.compile(r'PresentationIndex\[(.*?)\]') 3)然后我得到匹配项使用 group() 从结果中取出并将这些值存储在一个新列表中 4)然后我通过首先将项目转换为 int,然后排序,然后将其转换回像这样的字符串来对列表进行数字排序 5)现在我迭代通过该列表并在 6)中插入单词 PresentationIndex 和方括号)使用现在排序的 PresentationIndex 列表,我遍历其中的每一个。对于每次迭代,我都会遍历整个输出文本文件以搜索相关行并将其附加到最终列表中。这样我就可以按照我想要的顺序获得输出。

我从一个大约 32,000 行的文件开始。做这个大概花了3个小时...

标签: pythonsortingbrackets

解决方案


这可能不是最理想的,但应该可以解决问题:

import re
from collections import OrderedDict

my_string = '''DecodingIndex[ 1]   PresentationIndex[ 2]
DecodingIndex[ 2]   PresentationIndex[ 3]
DecodingIndex[ 3]   PresentationIndex[ 1]'''

my_list = list(my_string.split("\n"))

my_dict = {}

for x in my_list:
    match = re.search("\[\s*(\d+)\s*\]$", x)
    my_dict[match.group(1)] = x

ordered_dict = OrderedDict(sorted(my_dict.items(), key=lambda t: t[0]))
print(ordered_dict)

对您来说可能很慢的部分是读取文件?这一切都应该运行得非常快。我从一个字符串开始,假设您可以将文件转换为字符串。我拆分了字符串,\n但您也可以只读取文件,因此每一行都是列表中的一个项目。

然后我循环它并用正则表达式匹配你想要排序的那个数字。使该值key在 a 中dict。然后使用collections按键对字典进行排序。全部做完!希望有帮助。


推荐阅读