[2.5.1.1/dictionary] Change sorting order?

Arnaud Delobelle arnodel at googlemail.com
Sun Jan 24 23:55:53 CET 2010


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]

It would make sense to keep track of the indices where the first word
starting with a certain letter starts in the earlier part of the code
and to use it now to 'rotate' the list.

> print result
> ==========
>
> Thanks again.

-- 
Arnaud



More information about the Python-list mailing list