
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Fractional Frequency of elements in List
When it is required to find the fractional frequency of elements in a list, a dictionary comprehension, a simple iteration and the ‘Counter’ method is used.
Example
Below is a demonstration of the same −
from collections import Counter my_list = [14, 15, 42, 60, 75, 50, 45, 55, 14, 60, 48, 65] print("The list is :") print(my_list) my_num = {index : 0 for index in set(my_list)} my_denominator = Counter(my_list) my_result = [] for element in my_list: my_num[element] += 1 my_result.append(str(my_num[element]) + '/' + str(my_denominator[element])) print("The result is :") print(my_result)
Output
The list is : [14, 15, 42, 60, 75, 50, 45, 55, 14, 60, 48, 65] The result is : ['1/2', '1/1', '1/1', '1/2', '1/1', '1/1', '1/1', '1/1', '2/2', '2/2', '1/1', '1/1']
Explanation
The required packages are imported into the environment.
A list of integers is defined and is displayed on the console.
A dictionary comprehension is used to get unique elements from the list.
This is assigned to a variable.
A counter is created from the list.
An empty list is defined.
The list is iterated over, and the ‘/’ operator is used to add specific elements to the empty list using ‘append’ method.
This is the output that is displayed on the console.
- Related Questions & Answers
- Python – Restrict Elements Frequency in List
- List frequency of elements in Python
- Python – Count frequency of sublist in given list
- Python – Adjacent elements in List
- Matplotlib – Make a Frequency histogram from a list with tuple elements in Python
- Find sum of frequency of given elements in the list in Python
- Python – Extract elements with equal frequency as value
- Python – Combine list with other list elements
- Python – List Elements Grouping in Matrix
- Python – Sort String list by K character frequency
- Python – Rows with all List elements
- Python – Concatenate Rear elements in Tuple List
- Python – Extract elements from Ranges in List
- Python – Check alternate peak elements in List
- Python – Calculate the percentage of positive elements of the list
Advertisements