开发者

Python sort items by specific defined rule

开发者 https://www.devze.com 2023-01-27 00:59 出处:网络
say i have a dict: d = {\'Abc\':5,\'Jack\':4,\'amy\':9,\'Tom\':0,\'abc\':5} If i want to write a function such that if i pass that function to the built-in sort function, eg. list(d).sort(function),

say i have a dict: d = {'Abc':5,'Jack':4,'amy':9,'Tom':0,'abc':5}

If i want to write a function such that if i pass that function to the built-in sort function, eg. list(d).sort(function), the sort function will sort the list based on the values, of any have identical values, sort them by their keys(alphabetical order). So, in this case, d = {'Abc':5,'Jack':4,'amy':9,'Tom':0,'abc':5,'TAM':0} returns ['amy','Abc','abc','Jack','TAM','Tom'] The function should look something like this:

def arrange_items(something, thing,**may be a function**): 
        if something < thing:
                return -1 
        elif something > thing:
                return 1 
        etc

if i call some_list.sort(arrange_items), i should get a sorted list back

Thank you in advance

Modification of specification(Another question): if i have a dict of twitter users name, the dict is in this format:

dict = {'JohnZ':{'name': Jonny Zue,'follow':'MiniT',}, etc} # JohnZ is one of the twitter user. The follow means people that JonhZ follows, in this case it is MiniT.

Popularity of a user means the number of people that follow this particular user, in the above example, the popularity of MiniT is at least one b/c there is at least one user who follow MiniT.

say i have a list of twitter user names, say L1 = ['JonhZ','MiniT',etc], and i want to sort L1 based on the users popularity (higher popularity comes first). dict is already defined开发者_Python百科 in global namespace(we can directly access dict).The requirement for this sort function is to use L1.sort(pass_function) How should i write the pass_function such that sort will automatically sort L1 based on the popularity of the users.

Thanks for helping


[k for k, v in sorted(d.iteritems(), key=lambda x: (-x[1], x[0].lower()))]

EDIT:

(I refuse to use the name "dict" since it shadows a builtin, and shadowing builtins is stupid)

L1.sort(key=lambda x: (-d.get(x, 0), x.lower()))


You can't achieve this with list(d).sort(function), because you'll get a list with dictionary keys. You can achieve your objective with alternative approach:

l1 = sorted(d.items(), key=lambda x: (x[1], x[0]))
l2 = sorted(l1, key=lambda x: x[1], reverse=True)
result = [x[0] for x in l2]

This approach converts dictionary to list of (key, value) tuples. Then l1 is sorted by values and l2 is sorted by keys. Since python has a stable sorting algorithm, the order of values is preserved for identical keys.

Edit: Ignacio Vazquez-Abrar's approach is similar, but more elegant, because the list need to be sorted only once.

0

精彩评论

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