5

我的正则表达式如下

    text = 'id 5 result pass
            id 4 result fail
            id 3 result fail
            id 2 result fail
            id 1 result pass'

    for i in re.finditer('id (.+?) result (.+)', text): 
         id = i.group(1)
         result = i.group(2)
         print 'id' 
         print 'result' 

输出正常。但是我如何反转它以以其他顺序获得结果,其中 id 将从 1 开始,通过或失败结果

4

4 回答 4

5

A good way is (which will be faster than using a lambda in the sorted):

sorted(re.finditer(...,text),key=attrgetter('group'),reverse=True):

Or you could turn the iterator into a list and reverse it:

for i in reversed(list(re.finditer('id (.+?) result (.+)', text))): 
于 2013-07-08T02:51:51.410 回答
4

将 finditer 调用分配给列表并将其反转。

matches = list(re.finditer(...))
matches.reverse()

for i in matches:
   # etc.
于 2013-07-08T02:56:20.080 回答
1

您可以按id. 如果记录最初是随机顺序的,这也可以正常工作。

for i in sorted(re.finditer('id (.+?) result (.+)', text), key=lambda m:int(m.group(1))):

在给出的示例中,排序具有 O(n) 复杂度,因为 timsort 将输入检测为单个“运行”

于 2013-07-08T03:00:47.013 回答
1

当使用 finditer更改文本时,我们希望首先发现更改,然后以相反的顺序进行更改。像这样的东西:

# Pass 1: Find all replacements without changing the text.
replacements = []
for mo in pattern.finditer(text):
    # This may be arbitrarily complicated...
    << compute old, new text based on mo >>
    replacements.append((old, new),)

# Pass 2: Safely make all replacements by making them in reverse order.
for old, new in reversed(replacements):
    text = text.replace(old, new)
于 2018-03-20T16:07:51.540 回答