2

I am trying to group this list together

Example input

M1 = [['a', 14], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]

Output

[['a',14,7,16],['b',3,15],['c',22,1,5]]

Meaning group all the 'a' value together same goes for 'b', 'c' and so on

Ken Uda
  • 45
  • 2

4 Answers4

1

Below I give an example with a dictionary output. Just in case a sublist has many number's, this will account for that and arrange it in the correct section in the correct format.

#Look at 'a'

x = [['a', 14,15], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]
dictX = {}
for lsts in x:
    if lsts[0] in dictX.keys():dictX[lsts[0]].extend(lsts[1:])
    else:dictX[lsts[0]] = lsts[1:]           

output

{'a': [14, 15, 7, 16], 'b': [3, 15], 'c': [22, 1, 5]}
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
0

You will need to iterate through the elements of M1. Each element you encounter will look like [ch, num] (e.g. ['b', 3]). To append the new num into the ch list, you'll first need to find the ch list, and then append num to the ch list. This indicates we should use a dict since we can look up by ch in O(1). Here's an implementation:

M1 = [['a', 14], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]

d = dict()
for ch, num in M1:
  if ch in d:
    d[ch].append(num)
  else:
    d[ch] = [num]

print(d)
l = list(groups.items())
print(l)
# `l` is a list of tuples. The first element of each tuple is the character; the second is the list of `num`s corresponding to that character. For your example, `l` will be:
# [('a',[14,7,16]),('b',[3,15]),('c',[22,1,5])]
joseville
  • 685
  • 3
  • 16
0

Here is one approach using pandas.

import pandas as pd

M1 = [['a', 14], ['a', 7], ['a', 16],['b', 3],['b', 15],['c', 22],['c', 1],['c', 5]]    
df = pd.DataFrame(M1, columns=['id', 'value'])

df = df.groupby(by='id')['value'].apply(list)

>>> df # already grouped as you want
    id
    a    [14, 7, 16]
    b        [3, 15]
    c     [22, 1, 5]
    Name: value, dtype: object

Afterwards, you can convert it to a dictionary like so

df = df.to_dict()

>>> df
    {'a': [14, 7, 16], 'b': [3, 15], 'c': [22, 1, 5]}

Or a list of lists if you need to

l = [[k] + v for k, v in df.items()] 

>>> l
    [['a', 14, 7, 16], ['b', 3, 15], ['c', 22, 1, 5]]
Camilo Martinez M.
  • 1,420
  • 1
  • 7
  • 21
-1

To get a list of lists (like your questions asks for) you can do something like this:

M1 = [['a', 14,15], ['a',7], ['a',16],['b',3],['b',15],['c',22],['c',1],['c',5]]
output = {}
for l in M1:
    if l[0] in output.keys():
        output[l[0]].append(l[1:][0])
    else:
        output[l[0]] = l[1:]

# Output is now a dictionary. You can stop here if you're fine with a dictionary, or continue on from here

listOfLists = []
for k, v in output.items():
    listOfLists.append([k, *v])

And then the results:

>>> print(output)
# {'a': [14, 15, 7, 16], 'b': [3, 15], 'c': [22, 1, 5]}

>>> print(listOfLists)
# [['a', 14, 15, 7, 16], ['b', 3, 15], ['c', 22, 1, 5]]
12944qwerty
  • 2,001
  • 1
  • 10
  • 30