Capturing named groups in regex with re.findall

后端 未结 3 1270
忘了有多久
忘了有多久 2021-01-02 20:28

When I was trying to answer this question: regex to split %ages and values in python I noticed that I had to re-order the groups from the result of findall. For example:

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-02 20:38

    Per the OP's comment on my first answer: If you are simply trying to reorder a list of 2-tuples like this:

    [('34', 'passed'), ('23', 'failed'), ('46', 'deferred')]
    

    ... to look like this, with individual elements reversed:

    [('passed', '34'), ('failed', '23'), ('deferred', '46')]
    

    There's an easy solution: use a list comprehension with the slicing syntax sequence[::-1] to reverse the order of the elements of the individual tuples:

    a = [('34', 'passed'), ('23', 'failed'), ('46', 'deferred')]
    b = [x[::-1] for x in a]
    print b
    

提交回复
热议问题