📜  Python - 百分比范围内的元素频率(1)

📅  最后修改于: 2023-12-03 14:45:54.771000             🧑  作者: Mango

Python - 百分比范围内的元素频率

有时,我们需要确定在特定范围内出现给定元素的频率百分比。 在Python中,我们可以使用列表解析和内置函数来解决此问题。

计算百分比

我们可以使用以下公式计算给定元素在范围内出现的频率百分比:

$$ frequency\ percentage = \frac{count\ of\ elements\ in\ range}{total\ count\ of\ elements} * 100 $$

首先,我们需要找到在特定范围内出现给定元素的总次数。 然后,我们可以将其除以列表中的总元素数并将其乘以100以获取百分比。

方法1:列表解析

我们可以使用列表解析来计算在范围内出现给定元素的总次数,并将计数除以总元素数以计算百分比。

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# The range within which we want to check the frequency of the element
start_range = 2
end_range = 8

# The element whose frequency we want to calculate
elem = 2

# Using list comprehension to count the frequency of the element
count = len([i for i in lst[start_range:end_range+1] if i == elem])

# Calculating the frequency percentage
freq_percentage = (count / len(lst[start_range:end_range+1])) * 100

print(f"The frequency percentage of {elem} between the range {start_range} to {end_range} is {freq_percentage}%")

输出:

The frequency percentage of 2 between the range 2 to 8 is 25.0%
方法2:内置函数

Python内置了一系列方便的函数,其中包含用于计算给定元素在列表中出现次数的计数函数。 我们可以使用此函数计算在范围内出现给定元素的总次数,并将其除以总元素数以计算百分比。

lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# The range within which we want to check the frequency of the element
start_range = 2
end_range = 8

# The element whose frequency we want to calculate
elem = 2

# Using built-in function to count the frequency of the element
count = lst[start_range:end_range+1].count(elem)

# Calculating the frequency percentage
freq_percentage = (count / len(lst[start_range:end_range+1])) * 100

print(f"The frequency percentage of {elem} between the range {start_range} to {end_range} is {freq_percentage}%")

输出:

The frequency percentage of 2 between the range 2 to 8 is 25.0%

无论您喜欢使用哪种方法,您现在已经知道如何计算在给定范围内出现给定元素的频率百分比。