[Wellington-pm] Select at random from a list
Grant McLean
grant at mclean.net.nz
Sun Jul 16 18:19:02 PDT 2006
On Sat, 2006-07-15 at 16:49 +1200, michael at diaspora.gen.nz wrote:
> Philip Plane writes:
> >$mp3 = $playlist[int(rand(scalar(@playlist)))];
>
> One feature I found when playing with Python recently that I really
> liked was a better method of choosing a random element from an array:
>
> >>> import random
> >>> random.choice([1,2,3,4])
> 2
> >>> random.sample([1,2,3,4], 2)
> [4, 2]
> >>> x = [1,2,3,4]
> >>> random.shuffle(x)
> >>> x
> [3, 1, 2, 4]
>
> A quick look on CPAN doesn't seem to reveal such a convenient module.
> Anyone seen one, or should I think about a port?
It does seem like the sort of thing that ought to be on CPAN, but I'm
not aware of any implementation either.
The TODO list for the List::MoreUtils module does include 'random_item'
so you could submit a patch to the maintainer of that module. That
approach would have the added advantage of not leaving you with the
burden of maintaining the code :-)
http://search.cpan.org/dist/List-MoreUtils/lib/List/MoreUtils.pm#TODO
Cheers
Grant
More information about the Wellington-pm
mailing list