简体   繁体   English

Python仅对序列中的子序列进行排序

[英]Python only sort sub-sequences in a sequence

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. 对于每一行,如果{}中出现多个数字,我想在每个方括号中对它们进行排序(升序sort),同时保持其余的顺序。 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. 我的想法是将每一行都转换成一个列表,但是后来我完全陷入了困境。

One-liner using re.sub function. 一线使用re.sub功能。

>>> 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

您可以使用嵌套列表推导: [[f for s in sequences for f in sorted(s)] for sequences in lines]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM