sorting - Change the way sorted works in Python (different than alphanumeric) -
i'm representing cards in poker letters (lower , uppercase) in order store them efficiently. need custom sorting function allow calculations them.
what fastest way sort letters in python using
['a', 'n', 'a', 'n', 'b', 'o', ....., 'z']
as ranks rather than
['a', 'b', 'c', 'd', 'e', 'f', ....., 'z']
which default?
note, sorting derived from:
import string c = string.letters[:13] d = string.letters[13:26] h = string.letters[26:39] s = string.letters[39:] 'a' = 2 of clubs 'n' = 2 of diamonds 'a' = 2 of hearts 'n' = 2 of spades etc
you can provide key
function sorted
, function called each element in iterable , return value used sorting instead of elements value.
in case might following:
order = ['a', 'n', 'a', 'n', 'b', 'o', ....., 'z'] sorted_list = sorted(some_list, key=order.index)
here brief example illustrate this:
>>> order = ['a', 'n', 'a', 'n'] >>> sorted(['a', 'n', 'n', 'a'], key=order.index) ['a', 'n', 'a', 'n']
note make more efficient may want use dictionary lookup key
function instead of order.index
, example:
order = ['a', 'n', 'a', 'n', 'b', 'o', ....., 'z'] order_dict = {x: i, x in enumerate(order)} sorted_list = sorted(some_list, key=order_dict.get)
Comments
Post a Comment