random.shuffle question
Greg Ewing
see_reply_address at something.invalid
Tue Sep 10 02:04:22 EDT 2002
Erik Max Francis wrote:
> You could simply chop up the list, shuffle the part that you want, and
> then reassemble it:
Or for more fun, you could use the handy class
attached below, and simply say:
random.shuffle(sublist(mylist, 4, 8))
#-------------------------------------------
class sublist:
"""sublist(x, i, j) is an object which
behaves like x[i:j] except that changes
to it are reflected in x. (This version
only handles getting and setting single
items.)"""
def __init__(self, base, begin, end):
self.base = base
self.begin = begin
self.end = end
def __len__(self):
return self.end - self.begin
def __getitem__(self, i):
return self.base[self.begin + i]
def __setitem__(self, i, x):
self.base[self.begin + i] = x
if __name__ == "__main__":
import random
l = range(20)
print "Before:", l
random.shuffle(sublist(l, 5, 15))
print "After:", l
#-------------------------------------------
--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
More information about the Python-list
mailing list