Printing counts of elements in a Tuple based on condition

470 views Asked by At

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))
2

There are 2 answers

0
Martijn Pieters On BEST ANSWER

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)
0
Brad Solomon On

You can also use pandas.cut here along with pandas.Series.value_counts. .cut:

Return indices of half-open bins to which each value of x belongs.

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

counts = pd.cut(li, bins=[-float('inf'), 50., 85., float('inf')],
                labels=['<50', '50-85', '>85']).value_counts()

Your result will be a pandas Series.

print(counts)
<50      5
50-85    1
>85      1

Note the parameter right

Indicates whether the bins include the rightmost edge or not. If right == True (the default), then the bins [1,2,3,4] indicate (1,2], (2,3], (3,4].

Lastly if you don't specify labels, they'll default to:

counts = pd.cut(li, bins=[-float('inf'), 50., 85., float('inf')]).value_counts()

print(counts)
(-inf, 50.0]    5
(50.0, 85.0]    1
(85.0, inf]     1