Parsing a python list with a character in each element

I have a python list with elements that are a list containing a string of letters and numbers, and I was wondering how I could split the list into a character at the beginning of a line without creating an instruction for each character. So I want to split mylist into lists a, b and c.

mylist = [['a1'],['a2'],['c1'],['b1']]
a = [['a1'],['a2']]
b = [['b1']]
c = [['c1']]

It is important that I save them as a list of lists (although this is only one item in each small list).

thank

+5
source share
3 answers

This will work:

import itertools as it

mylist  = [['a1'],['a2'],['c1'],['b1']]
keyfunc = lambda x: x[0][0]

mylist = sorted(mylist, key=keyfunc)
a, b, c = [list(g) for k, g in it.groupby(mylist, keyfunc)]

The line in which it is used sorted()is necessary only if the elements in are mylistno longer sorted by the character at the beginning of the line.

EDIT:

, ( ) ( Python 2.7+) :

result_dict = {k: list(g) for k, g in it.groupby(mylist, keyfunc)}

:

result_dict['a']
> [['a1'],['a2']]

result_dict['b']
> [['b1']]

result_dict['c']
> [['c1']]
+4

mylist = [['a1'],['a2'],['c1'],['b1']]

from collections import defaultdict

dicto = defaultdict(list)

for ele in mylist:
    dicto[ele[0][0]].append(ele)

:

>>> dicto
defaultdict(<type 'list'>, {'a': [['a1'], ['a2']], 'c': [['c1']], 'b': [['b1']]})

, ; ,

>>> dicto['a']
[['a1'], ['a2']]
+2

You can also get these sublists using a simple function:

def get_items(mylist, letter):
  return [item for item in mylist if item[0][0] == letter]

An expression item[0][0]simply means getting the first letter of the first element of the current element. Then you can call a function for each letter:

a = get_items(mylist, 'a')
b = get_items(mylist, 'b')
c = get_items(mylist, 'c')
0
source

All Articles