简体   繁体   中英

Alternative to list.count( ) in python

I am looking to be able to write an alternative code to the built in count in python: This code works

def count(element,seq):
    """Counts how often an element occurs
    ...in a sequence"""
    mycount = seq.count(element)
    return mycount

but I would like to write it in a for loop (or another way?), I've got this far:

def count(element,seq):
    """Counts how often an element occurs
    ...in a sequence"""
    for i in seq:
        if  element == seq:
            print i

I'm not sure how to return the re-occuring elements as an integer. Any help appreciated!!

Use sum() and a generator expression:

def count(element,seq):
    """Counts how often an element occurs
    ...in a sequence"""
    return sum(1 for i in seq if i == element)

What this does: it loops over each item in seq , and if that item is equal to element , it generates a 1 , which sum() adds up to get the total count.

Using a generator expression like this means that there is only ever one item of seq being referenced at a time, allowing you to scan huge sequences efficiently.

How about this:

def count(element,seq):
    """Counts how often an element occurs
    ...in a sequence"""
    count = 0
    for i in seq:
        if  element == i:
            count += 1
    return count

What this does: it loops over each item in seq , and if that item is equal to element , it adds 1 to count (which is initially 0 ) and then returns count after the loop ends.

Using a for loop like this means that there is only ever one item of seq being referenced at a time, allowing you to scan huge sequences efficiently.

Just another way

from collections import Counter
def count(elem, seq):
    return Counter(seq)[elem]

And Just another way

>>> from itertools import compress
>>> len(list(compress(seq, [e == 1 for e in seq])))
3

with a little variation

>>> sum(1 for _ in compress(seq, [e == 1 for e in seq]))
3

another implementation using filter

>>> len(filter(None, [e == 1 for e in seq]))
3

If you want to write it as a for loop, as per your example:

def count(element, sequence):
    c = 0
    for e in sequence:
        if e == element:
            c += 1
    return c

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