Python | Percentage occurrence at index

Sometimes while dealing with statistics, we might come across this particular problem in which we require to find the percentage of occurrence of element at particular index in list of list. Let’s discuss certain ways in which this can be done.

Method #1 : Using loop + list comprehension
We can perform this particular task using the loop for each list index, and for that we can compute the percentage occurrence of element using the list comprehension logic.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# index percentage calculation of element
# using loop + list comprehension
  
# initializing test list
test_list = [[3, 4, 5], [2, 4, 6], [3, 5, 4]]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using loop + list comprehension
# index percentage calculation of element
res = []
for i in range(len(test_list[1])):
    res.append(len([j[i] for j in test_list if j[i]== 4 ])/len(test_list))
  
# print result
print("The percentage of 4 each index is : " + str(res))

chevron_right


Output :

The original list : [[3, 4, 5], [2, 4, 6], [3, 5, 4]]
The percentage of 4 each index is : [0.0, 0.6666666666666666, 0.3333333333333333]

 

Method #2 : Using zip() + count() + list comprehension
This particular task can also be performed using the combination of above functions. The count and zip function do the task of percentage computation and grouping respectively.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# index percentage calculation of element
# using zip() + count() + list comprehension
  
# initializing test list
test_list = [[3, 4, 5], [2, 4, 6], [3, 5, 4]]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using zip() + count() + list comprehension
# index percentage calculation of element
res = [sub.count(4)/len(sub) for sub in zip(*test_list)]
  
# print result
print("The percentage of 4 each index is : " + str(res))

chevron_right


Output :

The original list : [[3, 4, 5], [2, 4, 6], [3, 5, 4]]
The percentage of 4 each index is : [0.0, 0.6666666666666666, 0.3333333333333333]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.