[2.5.1.1/dictionary] Change sorting order?

Arnaud Delobelle arnodel at googlemail.com
Fri Jan 22 16:19:44 CET 2010


Gilles Ganault <nospam at nospam.com> writes:

> On Fri, 22 Jan 2010 09:49:32 -0500, Dave Angel <davea at ieee.org> wrote:
>>Seems to me the other solutions I've seen so far are more complex than 
>>needed.  I figure you either want an unordered list, in which case you 
>>could use random.shuffle(), or you want a list that's sorted, but starts 
>>somewhere in the middle, at an arbitrary place, goes to the end, and 
>>wraps back to the beginning.  So use random.randint() to choose an index 
>>within the list, and concatenate two slices of the list, based on that 
>>index in reverse order.
>
> Yes, this is exactly what I need: Start listing items from a given
> index (actually, using a character since the list contains names) all
> the way to the end of the list; If the character wasn't the very
> first, go back to the first time and display the list until we get to
> the current character.
>
> Python is so feature-rich, I'm sure there's a much simpler way to do
> this than this crappy code of mine:
>
> =============
> connected = []
> connected.append("0dummy")
> connected.append("aa")
> connected.append("bb")
> connected.append("cc")
>
> index = 0
> for item in connected:
> 	#For testing purposes;
> 	#Final code will read/increment character from file
> 	if item[index] == "b":
> 		break
> 	else:
> 		index = index + 1
>
> #Print items between current character and end of list
> tempindex = index
> while(tempindex < len(connected)):
> 	print connected[tempindex]
> 	tempindex = tempindex + 1
>
> #if current letter not first character,
> #display beginning of list up to current character
> if index != 0:
> 	tempindex = 0
> 	while tempindex < index:
> 		print connected[tempindex]
> 		tempindex = tempindex + 1
> =============
>
> Thank you for any help

Here's a straightforward way to do it, taking advantage of negative
indices (no doubt there are many others):

>>> connected = '0dummy aa bb cc'.split()
>>> connected
['0dummy', 'aa', 'bb', 'cc']
>>> startindex = random.randrange(len(connected))
>>> startindex
2
>>> for i in xrange(startindex - len(connected), startindex):
...     print connected[i]
... 
bb
cc
0dummy
aa
>>>

connected[-1] is the last element of connected
connected[-2] is the one before last
etc...

I'll let you figure out why the loop works as it does.

HTH

-- 
Arnaud




More information about the Python-list mailing list