我有以下场景,其中文本文件具有类似于以下输出的内容:
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)我迭代文件中的每一行并将其存储到lines[]列表中
2)迭代lines[]列表中的每个项目,同时使用以下正则表达式模式re.compile(r'PresentationIndex\[(.*?)\]')
3)然后我使用 group() 从结果中获取匹配项并将这些值存储在新列表中
4)然后,我首先将项目转换为 int,然后排序,然后将其转换回字符串,对列表进行数字排序
5)现在我遍历该列表并插入单词PresentationIndex和方括号
6)使用现在已排序的PresentationIndex 列表,我迭代其中的每一个。对于每次迭代,我都会迭代整个输出文本文件以搜索关联的行并将其附加到最终列表中。这样我就可以按照我想要的顺序获得输出。
我从一个大约 32,000 行的文件开始。做这样的事情大约花了3个小时......
最佳答案
这可能不是最佳方案,但应该可以解决问题:
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
,但您也可以只读取文件,这样每一行都是列表中的一个项目。
然后我循环它并用正则表达式匹配您想要排序的数字。将该值设为 dict
中的key
。然后使用collections
按键对字典进行排序。全做完了!希望有帮助。
关于python - 如何按方括号之间的内容进行数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52609724/