开发者

Python sorting a list of strings

开发者 https://www.devze.com 2023-03-09 21:58 出处:网络
How would I sort this? >>> list = ["a_0","a_1","a_2","a_3","a_10","a_11","a_23","a_5","a_6","a_5

How would I sort this?

>>> list = ["a_0","a_1","a_2","a_3","a_10","a_11","a_23","a_5","a_6","a_5"]
>>> sorted(list)
['a_0', 'a_1', 'a_10', 'a_11', 'a_2', 'a_23', 'a_3', 'a_5', 'a_5', 'a_6']>

What I need it to be is:

开发者_开发知识库
['a_0', 'a_1', 'a_2', 'a_3', 'a_5', 'a_5', 'a_6, 'a_10', 'a_11', 'a_23']>

So it's sorted based on the "number".


do you mean this: sorted(list, key=lambda d: int(d[2:])) ?


You need to write a "key function" that translates your string into a search key that has the ordering you want. For example:

def key(k):
    s, sep, i = k.partition('_')
    return (s, int(i))

>>> L = ["a_0","a_1","b_2","c_2","a_10","a_11","a_23","b_5","a_6","c_5"]
>>> sorted(L, key=key)
['a_0', 'a_1', 'a_6', 'a_10', 'a_11', 'a_23', 'b_2', 'b_5', 'c_2', 'c_5']
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号