Python - 百分比范围内的元素频率
给定一个元素列表和百分比范围,任务是编写一个Python程序来提取频率出现在给定范围内的所有元素。
Input : test_list = [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8], strt, end = 13, 25
Output : [6, 7, 8]
Explanation : 21.4, 14.2, 14.2 is percentage presence of 6, 7, 8 respectively.
Input : test_list = [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8], strt, end = 13, 20
Output : [7, 8]
Explanation : 14.2, 14.2 is percentage presence of 7, 8 respectively.
存在百分比可以通过以下公式简单计算:
Frequency of the element present in the list/ total no. of elements in the list
方法#1:使用Counter() + set() + loop + len()
在这种情况下,使用循环提取所有元素的频率。下一步是获取列表的元素集并检查频率是否在指定的范围内。
Python3
# Python3 code to demonstrate working of
# Element frequencies in percent range
# Using Counter() + set() + loop + len()
from collections import Counter
# initializing list
test_list = [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
# initializing percent ranges
strt, end = 13, 25
# getting frequencies
freqs = dict(Counter(test_list))
# computing percents and assigning
res = []
for ele in set(test_list):
percent = (freqs[ele] / len(test_list)) * 100
if percent >= strt and percent <= end:
res.append(ele)
# printing result
print("Elements within range of frequencies : " + str(res))
Python3
# Python3 code to demonstrate working of
# Element frequencies in percent range
# Using Counter() + loop + len()
from collections import Counter
# initializing list
test_list = [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
# initializing percent ranges
strt, end = 13, 25
# getting frequencies
freqs = dict(Counter(test_list))
# computing percents and assigning
# iterating from dictionary
res = []
for ele in freqs:
percent = (freqs[ele] / len(test_list)) * 100
if percent >= strt and percent <= end:
res.append(ele)
# printing result
print("Elements within range of frequencies : " + str(res))
输出:
The original list is : [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8]
Elements within range of frequencies : [6, 7, 8]
方法#2:使用Counter() + loop + len()
这以几乎相似的方式执行任务,主要区别在于迭代计数器键而不是列表元素,因为它们提供类似的输出。
蟒蛇3
# Python3 code to demonstrate working of
# Element frequencies in percent range
# Using Counter() + loop + len()
from collections import Counter
# initializing list
test_list = [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8]
# printing original list
print("The original list is : " + str(test_list))
# initializing percent ranges
strt, end = 13, 25
# getting frequencies
freqs = dict(Counter(test_list))
# computing percents and assigning
# iterating from dictionary
res = []
for ele in freqs:
percent = (freqs[ele] / len(test_list)) * 100
if percent >= strt and percent <= end:
res.append(ele)
# printing result
print("Elements within range of frequencies : " + str(res))
输出:
The original list is : [4, 6, 2, 4, 6, 7, 8, 4, 9, 1, 4, 6, 7, 8]
Elements within range of frequencies : [6, 7, 8]