如何不使用正则表达式,基于元素中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:
entry.split('Count=')[1]splits the string atCount=and grabs the part after this substring—this gives us something like'1,lp-isD=2'or'3075,lp-gsD=5'..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').- 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
相关产品推荐
相关产品推荐

