You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用正则表达式,基于元素中Count=后的数值排序列表?

Sort List by Variable-Length Number After 'Count=' (No Regex Needed)

Got it! Since you don't want to use regular expressions and are dealing with a large dataset, we can leverage Python's built-in string split() method—it's efficient and straightforward for this scenario.

Here's the solution:

First, let's define your original list:

log_entries = [
    '16:11:40.894 0,Type=IsXover,Count=1,lp-isD=2',
    '16:11:40.894 0,Type=IsXover,Count=54,lp-xsD=1',
    '16:11:40.894 0,Type=IsXover,Count=201,lr-isD=3',
    '16:11:40.894 0,Type=IsXover,Count=3075,lp-gsD=5'
]

To sort the list in ascending order based on the number after Count=:

log_entries.sort(key=lambda entry: int(entry.split('Count=')[1].split(',')[0]))

How it works:

  1. entry.split('Count=')[1] splits the string at Count= and grabs the part after this substring—this gives us something like '1,lp-isD=2' or '3075,lp-gsD=5'.
  2. .split(',')[0] takes that result and splits it at the first comma, grabbing the first part (which is exactly the number string we need, e.g., '1' or '3075').
  3. We convert that string to an integer (int(...)) so the sort uses numeric order instead of lexicographical order.

For descending order:

Just add reverse=True to the sort call:

log_entries.sort(key=lambda entry: int(entry.split('Count=')[1].split(',')[0]), reverse=True)

This approach is fast because split() is a highly optimized native string operation, making it perfect for large datasets—no regex overhead required.

内容的提问来源于stack exchange,提问作者seyet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:25:54