简体   繁体   中英

How do you tally the amount of times a item in appears from a randomly list?

How do you tally the amount of times a item in appears from a random list?

Because at the moment i am am doing a un-boxing simulator for team fortress 2 and i have done it so that u can get a random strange 99% chance or an UNUSUAL 1% chance and i wish to know how to tally how many unusuals you have un-boxed.

def no():
    print "thankyou for playing crate unboxing simulator!"
    time.sleep(1)
    print "copyright Tristan Cook"
    time.sleep(1)
    print "You unboxed.."
    time.sleep(1)

i need something just there saying the amount of unusuals they have unboxed. Im looking for something i can just copy and paste cause i'm quite new to python (this is my first program and its 359 lines long xD)

Try this:

l =[...]
unusuals = l.count(unusual1)+l.count(unusual2)+...

You can use count from itertools .

>>> l=[random.randrange(0,10) for i in range(100)]
>>> l
[7, 1, 8, 6, ..., 8, 4]

>>> from itertools import count
>>> dict([(i,l.count(i)) for i in l])
{0: 5, 1: 12, 2: 6, 3: 9, 4: 13, 5: 11, 6: 11, 7: 9, 8: 12, 9: 12}

and to select only the value < 10% for instance:

>>> dict([(i,l.count(i)) for i in l if l.count(i)<(0.1*len(l))])
{0: 5, 2: 6, 3: 9, 7: 9}

Edit: And, as suggested by Pablo Moretti, with collections.counter :

>>> from collections import Counter
>>> c=Counter(l)
>>> [i for i in c if c[i]<(0.1*len(l))]
[0, 2, 3, 7]

or

>>> [(i, c[i]) for i in c if c[i]<(0.1*len(l))]
[(0, 5), (2, 6), (3, 9), (7, 9)]

And to have the 4 least common elements:

>>> c.most_common()[:len(c)-5:-1]
[(0, 5), (2, 6), (7, 9), (3, 9)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM