King
King

Reputation: 451

How to group list by numbers

Hello i have a list of the sort:

lst = [0.0000,0.0542,0.0899,0.7999,0.9999,1.8754]

The list keeps going.

Is there any way i can group the by one? Like for example every value that is between 0 to 1, and 1 to 2 etc.

As Id like to reppresent it on matplotlib of the count of numbers per group.

I tried everything but no success.

Upvotes: 0

Views: 1118

Answers (2)

Pablo C
Pablo C

Reputation: 4761

You can use numpy and numpy_indexed:

import numpy as np
import numpy_indexed as npi

lst = [0.0000,0.0542,0.0899,0.7999,0.9999,1.8754]

npi.group_by(np.trunc(lst), lst)

Output

(array([0., 1.]),
 [array([0.    , 0.0542, 0.0899, 0.7999, 0.9999]), array([1.8754])])
#keys and groups

You can easily install the library with:

> pip install numpy-indexed

Upvotes: 1

thornejosh
thornejosh

Reputation: 148

There is a nice library named itertools which has a function called groupby which can help you here. It collects adjacent values in a list together based on a predicate.

from itertools import groupby

lst = [0.0000,0.0542,0.0899,0.7999,0.9999,1.8754]
grouped_lst = [list(g) for k,g in groupby(lst, lambda x:int(x))]

Output:

[[0.0, 0.0542, 0.0899, 0.7999, 0.9999], [1.8754]]

lambda x:int(x) is the predicate here. int will convert your values to an integer i.e remove the decimal point. You can then loop over these 'groups' and convert them to a list using list(g).

Note this method will only work if your list is sorted. Please sort your list beforehand if it may not be sorted.

Upvotes: 1

Related Questions