count objects in a list and random numb gen

Bart Nessux bart_nessux at hotmail.com
Fri Jan 9 00:57:27 CET 2004


Paul Rubin wrote:
> Bart Nessux <bart_nessux at hotmail.com> writes:
> 
>>New to Python... trying to figure out how to count the objects in a
>>list and then map the count to the objects or convert the list to a
>>dict... I think the latter would be better as I need a number
>>associated with each entry. Any pointers?
> 
> 
> I'm sorry but I just can't understand the above description

I want to count the objects in a list. len works well for this. Once I 
have a count, I want to map that count to the items in the list like this:

entry one is 1
entry two is 2
entry three is 3
...

This is why I thought a dictionary may be better suited for this.

> 
> 
>>Also, does this bit of code look to be truely random?
>>
>>def random_number_gen():
>>    winner = []	
>>    winner.append(random.sample(xrange(100000), 1))	
>>    print winner	
> 
> 
> If you want to choose one random winner out of a list, you can say
> print random.randint(100000).  
> 
> Note that Python's random function doesn't try to be really seriously
> random, but only to have reasonable statistical properties.  If you
> need random numbers that can stand up to an adversary (e.g. you're
> using it in an online game where the winners get substantial prizes),
> you shouldn't generate them with the random module.

I think random.sample is better than you think:

sample(  population, k)

Returns a new list containing elements from the population while leaving 
the original population unchanged. The resulting list is in selection 
order so that all sub-slices will also be *valid random samples*. This 
allows raffle winners (the sample) to be partitioned into grand prize 
and second place winners (the subslices).






More information about the Python-list mailing list