Python – 列表中元素的小数频率
给定一个列表,获取每个位置的每个元素的分数频率。
Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 4]
Output : [‘1/4’, ‘1/3’, ‘2/4’, ‘1/1’, ‘1/1’, ‘2/3’, ‘3/4’, ‘3/3’, ‘4/4’]
Explanation : 4 occurs 1/4th of total occurrences till 1st index, and so on.
Input : test_list = [4, 5, 4, 6, 7, 5]
Output : [‘1/2’, ‘1/2’, ‘2/2’, ‘1/1’, ‘1/1’, ‘2/2’]
Explanation : 4 occurs 1/2th of total occurrences till 1st index, and so on.
方法:使用 Counter() + 循环 + 字典理解
在此,我们使用 Counter() 来获取列表中每个元素的频率并形成分数的分母部分。对于每个元素,分子被初始化为 0。然后使用循环将数字器中的元素相加,并以分母中的总频率连接。
Python3
# Python3 code to demonstrate working of
# Fractional Frequency of elements in List
# Using Counter() + loop + dictionary comprehension
from collections import Counter
# initializing list
test_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6]
# printing original list
print("The original list is : " + str(test_list))
# initializing numerator
number = {idx : 0 for idx in set(test_list)}
# initializing denominator
denom = Counter(test_list)
res = []
for ele in test_list:
# increasing counter
number[ele] += 1
res.append(str(number[ele]) + '/' + str(denom[ele]))
# printing result
print("Fractional Frequency List : " + str(res))
输出
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6]
Fractional Frequency List : ['1/5', '1/3', '2/5', '1/3', '1/1', '2/3', '3/5', '3/3', '4/5', '2/3', '5/5', '3/3']