Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group list by values

Let's say I have a list like this:

mylist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]] 

How can I most elegantly group this to get this list output in Python:

[["A", "C"], ["B"], ["D", "E"]] 

So the values are grouped by the secound value but the order is preserved...

like image 626
Veles Avatar asked Apr 17 '11 17:04

Veles


People also ask

How do you Groupby a list in Python?

You can group DataFrame rows into a list by using pandas. DataFrame. groupby() function on the column of interest, select the column you want as a list from group and then use Series. apply(list) to get the list for every group.

How do you group similar values in a list in Python?

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. Print the result.

How do you count values in a list Python?

The count() is a built-in function in Python. It will return you the count of a given element in a list or a string. In the case of a list, the element to be counted needs to be given to the count() function, and it will return the count of the element. The count() method returns an integer value.

How do you find the value of an element in a list?

To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.


1 Answers

values = set(map(lambda x:x[1], mylist)) newlist = [[y[0] for y in mylist if y[1]==x] for x in values] 
like image 116
Howard Avatar answered Nov 02 '22 12:11

Howard