Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find same values in a list and group together a new list?

Tags:

From this list:

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] 

I'm trying to create:

L = [[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]] 

Any value which is found to be the same is grouped into it's own sublist. Here is my attempt so far, I'm thinking I should use a while loop?

global n  n = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] #Sorted list l = [] #Empty list to append values to  def compare(val):    """ This function receives index values    from the n list (n[0] etc) """        global valin    valin = val     global count    count = 0      for i in xrange(len(n)):         if valin == n[count]: # If the input value i.e. n[x] == n[iteration]             temp = valin, n[count]              l.append(temp) #append the values to a new list              count +=1         else:           count +=1       for x in xrange (len(n)):     compare(n[x]) #pass the n[x] to compare function 
like image 647
Siii Avatar asked May 17 '15 23:05

Siii


People also ask

How do you group the same value in a list in Python?

groupby method. The groupby method will return a list of the tuples with the element and its group. In every iteration, convert the group of similar elements into a list. Append the list to the empty list.

How do you check if two values are the same in a list Python?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.


2 Answers

Use itertools.groupby:

from itertools import groupby  N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]  print([list(j) for i, j in groupby(N)]) 

Output:

[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]] 

Side note: Prevent from using global variable when you don't need to.

like image 139
aldeb Avatar answered Oct 02 '22 01:10

aldeb


Someone mentions for N=[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 1] it will get [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5], [1]]

In other words, when numbers of the list isn't in order or it is a mess list, it's not available.

So I have better answer to solve this problem.

from collections import Counter  N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] C = Counter(N)  print [ [k,]*v for k,v in C.items()] 
like image 25
Burger King Avatar answered Oct 02 '22 01:10

Burger King