Reputation: 323
My data looks like:
{12,} {13,} {10,}
{16,} {17, 15,} {22,}
{27,} {28,24,29,} {28,} {28,}
Each line is a sequence. For each line, if multiple numbers occur in { }, I want to sort them in each bracket(ascending sort ), while keeping the order of the rest. At last, I want to remove the brackets. So I want my output to be like this:
12, 13, 10
16, 15, 17, 22
27, 24, 28, 29, 28, 28
My thought was converting each line into a list, but then I was totally stuck.
Upvotes: 1
Views: 105
Reputation: 174706
One-liner using re.sub
function.
>>> s = """{12,} {13,} {10,}
{16,} {17, 15,} {22,}
{27,} {28,24,29,} {28,} {28,}"""
>>> print(re.sub(r'(?<=\d) +(?=\d)', ', ', re.sub(r'\{[^}]*\}', lambda m: ', '.join(sorted(re.findall(r'\d+', m.group(0)), key=lambda x: int(x))), s)))
12, 13, 10
16, 15, 17, 22
27, 24, 28, 29, 28, 28
Upvotes: 1
Reputation: 8910
You can use a nested list comprehension: [[f for s in sequences for f in sorted(s)] for sequences in lines]
Upvotes: 0