简体   繁体   中英

Sorting items using user-defined rule

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

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.

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

You might want to use sorted(iterable, key=function) . For example:

users = list(something) # a list of all the usernames 
user_profiles = dict(something) # a dict of the profiles

users_sorted = sorted(users, key=lambda un: user_profiles[un])

You could also overload the comparison operators like >, = and < by override __gt__(), __eq__() and __lt__() of your user profile data class. Please refer to Python 2.7 reference - Data model for further information.

Pack the args into tuples and sort them using the built in sort. Then unpack.

usernames = ['bbob', 'srv', 'gman', 'salmer']
firstnames = ['Billy', 'Steve', 'Guy', 'Steve']
tuples = zip(firstnames, usernames)
tuples.sort()
users_sorted, first_sorted = zip(*tuples)


>>>tuples
[('Billy', 'bbob'), ('Guy', 'gman'), ('Steve', 'salmer'), ('Steve', 'srv')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM