根据条件打印元组中元素的计数

Printing counts of elements in a Tuple based on condition

我想根据下面的 IF 语句打印项目数。我下面的是打印整个列表,7 次,以及每个项目 (1) 的计数。那不是我想要的。理想情况下会 return:

5

1

1

有什么想法吗?

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

您需要 'normalise' 您的价值观并计算它们;所以对于 i < 50 情况,您可以使用字符串 'below 50' 并计算 those 值:

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'])

请注意,我在 50 - 84 组中计算了 50。这会生成一个计数器对象,然后您只需询问特定的标签:

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

不过,您在这里并不真的需要 Counter();对于这种情况,只使用 3 个变量会更容易:

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)

您也可以在此处使用 pandas.cutpandas.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()

您的结果将是 pandas 系列。

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

注意参数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].

最后,如果您不指定标签,它们将默认为:

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