Home > database >  get such a number of elements as a percentage from a list
get such a number of elements as a percentage from a list

Time:04-05

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

CodePudding user response:

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)
  • Related