Python | Percentage occurrence at index

Python | Percentage occurrence at index

In this tutorial, we will explore how to calculate the percentage occurrence of an item at a specific index in a list of lists.

Objective:

Given a list of lists:

data = [["apple", "orange"], ["apple", "banana"], ["grape", "orange"], ["apple", "banana"]] 

For a given index, say index = 0, we want to find the percentage occurrence of each item at that index.

For the above data and given index, the output would be:

{ 'apple': 75.0, 'grape': 25.0 } 

Steps and Python Code:

  1. Extract Values at Given Index: Iterate over the lists and extract the value at the given index.

  2. Count Occurrences: Use a dictionary to track the number of occurrences of each item at the specified index.

  3. Calculate Percentage: Convert the counts into percentages based on the total number of lists.

data = [["apple", "orange"], ["apple", "banana"], ["grape", "orange"], ["apple", "banana"]] def percentage_occurrence(data, index): # Count occurrences at given index count_dict = {} for item in data: if item[index] in count_dict: count_dict[item[index]] += 1 else: count_dict[item[index]] = 1 # Calculate percentage occurrence total_lists = len(data) for key in count_dict: count_dict[key] = (count_dict[key] / total_lists) * 100 return count_dict index = 0 result = percentage_occurrence(data, index) print(result) # Output: {'apple': 75.0, 'grape': 25.0} 

Explanation:

  • We start by initializing an empty dictionary count_dict to store the counts of occurrences of items at the given index.

  • We then iterate over each list in data and increment the count of the item found at the given index.

  • After counting occurrences, we divide each count by the total number of lists (total_lists) to get the proportion. We then multiply by 100 to get the percentage.

Considerations:

  1. If the lists within data can have varying lengths, you might want to add a check to ensure the specified index exists in each list.

  2. This method assumes that the data contains lists with at least one element. If there's a chance it doesn't, you should add checks for that.

By following this tutorial, you've learned how to calculate the percentage occurrence of items at a specific index in a list of lists in Python.


More Tags

board-games charles-proxy upi .net-core apply validate-request profiling android-relativelayout system.text.json backwards-compatibility

More Programming Guides

Other Guides

More Programming Examples