Ever have two lists in python and you want to know what how much of one list the other contains? This code snippet will help you do that.
Percentage of one list in another.
"""
If you ever have two lists in python and wish to find out what percentage
one list has of another. You could use this code to find out.
"""
li1 = [1,2,3,4,5,6,7,8]
li2 = [1,2,3,4,9]
def listPercentage(list_to_check, parent_list):
"""
list_to_check is the list that you wish to know how many are in
another list. the parent_list is the list that you wish to see
how many the other list has of. You're checking what percentage
of the values in list_to_check are in parent_list.
"""
global list_percentage
perCounter = 0 #This counter is the key to finding out the percentage
"""
This FOR loop will run through the list you want to check, in this case
li2. If it finds that the number is in the parent list, in our case li1,
then it will add 1 to ther perCounter. At the end it divides the
perCounter by the parent list to get the percentage.
"""
for i in list_to_check:
if i in parent_list:
perCounter += 1
list_percentage = perCounter / float(len(parent_list))
list_percentage = list_percentage * 100
list_percentage = round(list_percentage)
return list_percentage
"""
The number that gets spit out to the screen is the percentage of li1
that li2 contains. If you run this bit of code exactly as it was
then you should get 25%, because that is how much of li1 that li2
contains.
"""
listPercentage(li2,li1)
print list_percentage
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.