Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting items using user-defined rule

Tags:

python

sorting

For instance, if I have a list of usernames, lets call this list L1, each username has his/her own profile (not stored in the L1). How should we write the function so that it will sort the usernames based on their actual name, if any usernames are tied for actual name, sort them by usernames. Note, I can get the username of the user by writing username[1], usernames are unique.

This is what I write:

def username(s1, s2):

    if s1 < s2:
        return -1
    elif s1 > s2:
        return 1
    else:
        # How can i sort them by username if they have the same actual name
        return 0
like image 887
John Avatar asked Oct 15 '25 14:10

John


2 Answers

You can always store the user names in a list, and then use the builtin sorted() function to make a sorted list of user names. Example:

users = ['Guido', 'Alex', 'Jack', 'Brian']
users_sorted = sorted(users)
print repr(users_sorted)

The result of this would be the list of users sorted alphabetically:

['Alex', 'Brian', 'Guido', 'Jack']

sorted takes several arguments, so if you want to define a special way to compare items in the list, you can do sorted(user, cmp=function), where function is your special comparison function.

See the docs on sorted() for more.

like image 182
Rafe Kettler Avatar answered Oct 17 '25 05:10

Rafe Kettler


sorted_username_list = sorted(usernames, key=user_sorter)

where:

usernames is a list

user_sorter is a function that takes a username and returns user's actual name

for same actual name, you can write the sorter function as this:

def user_sorter(x):
    return actual_name_of_user(x) + x
like image 39
mshsayem Avatar answered Oct 17 '25 03:10

mshsayem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!