Python按正则表达式排序列表

2024-10-02 18:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串列表,如下所示:

['dsafjhsafjkhefhajwejh;NR;123;dfgdsrhgjhdfgjhdsfjhg','jhfewrgjhdfjhgsufgssdfjgh;NR;3243;fgjdsgfjsdfkjgdf', ...]

此列表应按“;”之间的数字排序,数字总是在“NR;”之后,但并非每个字符串都包含数字。我已经尝试了数百种解决方案,但似乎没有一个有效。在

请帮帮我

编辑:

抱歉,我没有添加一些示例,因此它们是:

1。在

^{pr2}$
  1. 对于a中的项目: b、 追加(搜索(“(;NR;[0-9]*;)”,str(item)))

基本上我试过上面的代码和上面的一些变体,我记不清我试过的所有代码。在


Tags: 字符串代码编辑示例列表排序数字解决方案
2条回答

对列表排序总是接受“key”参数,并且可以将任意函数作为key传递。在您的情况下,函数应该执行以下操作:

  1. 找到“NR”后面的那部分字符串
  2. 找到该部分的初始部分,即“;”之前的部分,并将其解析为整数。在

这里有一种方法

def func(st): # I am using your first string as a running example in this code
    nr_part = st.split("NR;")[1]  # returns "3243;fgjdsgfjsdfkjgdf"
    int_part = nr_part.split(";")[0] # returns "3243"
    return int(int_part)

现在,您可以使用filter分离出包含“NR;”的字符串。在

^{2}$

最后,对结果列表进行排序很简单

aa = ['jhfewrgjhdfjhgsufgssdfjgh;NR;3243;fgjdsgfjsdfkjgdf', 'dsafjhsafjkhefhajwejh;NR;123;dfgdsrhgjhdfgjhdsfjhg']
a.sort(a, key=func)  # in place sorting

或者

sorted(a, key=func)  # Return a new sorted list

一些注意事项:必须确保列表中的所有字符串都能满足“NR;<;int>;”regex的假设,并且字符串的int部分不应太大,这样“int()”转换不会导致溢出。在

In [1]: a = ['jhfewrgjhdfjhgsufgssdfjgh;NR;3243;fgjdsgfjsdfkjgdf', 'dsafjhsafjkhefhajwejh;NR;123;dfgdsrhgjhdfgjhdsfjhg']

In [2]: a.sort(key=lambda x: x.split(';')[2])

In [3]: a
Out[3]:
['dsafjhsafjkhefhajwejh;NR;123;dfgdsrhgjhdfgjhdsfjhg',
 'jhfewrgjhdfjhgsufgssdfjgh;NR;3243;fgjdsgfjsdfkjgdf']

正如下面的@EMS所指出的,可以在NR;上拆分,如果始终存在NR;,则可以使用其第一部分。在

^{2}$

这将按顺序对列表进行排序。如果要创建列表的副本(为其分配一个新变量),可以使用sorted

b = sorted(a, key=lambda x: int(x.split("NR;")[-1].split(";")[0]))

端到端:

# Includes an entry without the `;NR;`
In [1]:     a = ['jhfewrgjhdfjhgsufgssdfjgh;NR;3243;fgjdsgfjsdfkjgdf', 'dsafjhsafjkhefhajwejh;NR;123;dfgdsrhgjhdfgjhdsfjhg', 'jhfewrgjhdfjhgsufgssdfjgh;fgjdsgfjsdfkjgdf']

# Remove any entry that doesn't have `;NR;` in it
In [2]:     a = filter(lambda x: ';NR;' in x, a)

# Sort with an integer version of the number found (rather than the string)
In [3]:     a.sort(key=lambda x: int(x.split("NR;")[-1].split(";")[0]))

In [4]: a
Out[4]:
['dsafjhsafjkhefhajwejh;NR;123;dfgdsrhgjhdfgjhdsfjhg',
 'jhfewrgjhdfjhgsufgssdfjgh;NR;3243;fgjdsgfjsdfkjgdf']

相关问题 更多 >