Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get such a number of elements as a percentage from a list

I would like to extract a percentage of elements from a list, remove them and add them to a new list.

Example :

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_list = get_purcentage(list, purcentage = 0.3)

# list should now be : 
# list =  [1, 2, 3, 4, 5, 6, 7]

# new_list should now be : 
# new_list =  [8, 9, 10]

Note: the order doesn’t matter, the items can be taken randomly

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this:

from random import shuffle

def get_percentage(lst, percentage):
    shuffle(lst)
    result = []
    for _ in range(int(len(lst) * percentage)):
        result.append(lst.pop())
    return result

Now you can use the new function in this way:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
new_lst = get_percentage(lst, percentage=0.3)

Important:

The get_percentage function modifies the input lst list!! The advantage is that it’s not creating a new list from scratch.

EDIT
If you don’t care about randomness then things are even easier:

def get_percentage(lst, percentage):
    result = []
    for _ in range(int(len(lst) * percentage)):
        result.append(lst.pop())
    return result

If it’s fine to create new lists and use the function in a different way:

def get_percentage(lst, percentage):
    n = int(len(lst) * percentage)
    return lst[n:], lst[:n]

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst, new_lst = get_percentage(lst, percentage=0.3)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading