Search code examples
pythontuplespython-collections

Printing counts of elements in a Tuple based on condition


I want to print the count of items based on the IF statement below. What I have below is printing the entire list, 7 times, and a count for each item (1). That is not what I want. Ideally it would return:

5

1

1

Any ideas?

from collections import Counter

li = (1,4,55,6,87,44,25)

for i in li:

    if i < 50:
        print(Counter(li))
    elif i > 50 and i < 85:
        print(Counter(li))
    else:
        print(Counter(li))

Solution

  • You need to 'normalise' your values and count those; so for the i < 50 case, you could use a string 'below 50' and count those values:

    counts = Counter(
        'below 50' if i < 50 else '50 - 84' if i < 85 else '85 or up' for i in li
    )
    print(counts['below 50'])
    print(counts['50 - 84'])
    print(counts['85 or up'])
    

    Note that I counted 50 in the 50 - 84 group. This produces a single counter object, and you then just ask for the specific labels:

    >>> counts = Counter(
    ...     'below 50' if i < 50 else '50 - 84' if i < 85 else '85 or up' for i in li
    ... )
    >>> counts
    Counter({'below 50': 5, '85 or up': 1, '50 - 84': 1})
    

    You don't really need a Counter() here, however; for this case it would be easier to just use 3 variables:

    below50 = 0
    between50_84 = 0
    over84 = 0
    
    for i in li:
        if i < 50:
            below50 += 1
        elif i < 85:
            between50_84 += 1
        else:
            over84 += 1
    
    print(below50)
    print(between50_84)
    print(over84)