[2.5.1.1/dictionary] Change sorting order?

Arnaud Delobelle arnodel at googlemail.com
Mon Jan 25 01:57:42 EST 2010


Arnaud Delobelle <arnodel at googlemail.com> writes:

> Gilles Ganault <nospam at nospam.com> writes:
>
>> On Fri, 22 Jan 2010 13:17:44 +0100, Gilles Ganault <nospam at nospam.com>
>> wrote:
>>>To avoid users from creating login names that start with digits in
>>>order to be listed at the top, I'd like to sort the list differently
>>>every minute so that it'll start with the next letter, eg. display the
>>>list from A...Zdigits the first time, then B...ZAdigits, etc.
>>
>> Thanks everyone for the great feedback. I ended up using
>> - a list instead of a dictionary to hold the list of names
>> - use the random library to pick a character from which to start
>> listing names (simpler than saving the next letter into a file, and
>> starting from this the next time the loop is gone through)
>>
>> For those interested, here's some working code:
>>
>> ==========
>> import random
>>
>> connected =
>> ["_test","-test","0test","1test","Aa","Aab","Bb","Bbbbb","Cc","Ccaaaaaa"]
>> connected.sort()
>>
>> #Fill list with non-duplicate first letter of all items
>> characters=[]
>> for name in connected:
>> 	char = name[0]
>> 	#if this character not in list, add to array
>> 	if not char in characters:
>> 		characters.append(char)
>
> characters = list(set(name[0] for name in connected))
>
>> #Pick a random character from which to start iterating
>> index = random.randint(0,len(characters)-1)
>> startch = characters[index]
>
> startch = random.choice(characters)
>
>> print "Will start from %s" % startch
>>
>> #Go through list starting with items that start with 'starch', and
>> rotate from beginning
>> result = [name for name in connected if name[0] >= startch] + [name
>> for name in connected if name[0] < startch]

I forgot this line:

result = sorted(connected, key=lambda name: name[0] < startch)

This takes advantage of the fact that timsort is stable.

So you could do it like this, assuming connected is sorted:

characters = list(set(name[0] for name in connected))
startch = random.choice(characters)
result = sorted(connected, key=lambda name: name[0] < startch)

If connected is not sorted, you could replace the last line with:

result = sorted(connected, key=lambda name: (name[0] < startch, name))

-- 
Arnaud



More information about the Python-list mailing list