user1403546
user1403546

Reputation: 1749

Python - split list of lists by value

I want to split the following list of lists

a = [["aa",1,3]
     ["aa",3,3]
     ["sdsd",1,3]
     ["sdsd",6,0]
     ["sdsd",2,5]
     ["fffffff",1,3]]

into the three following lists of lists:

a1 = [["aa",1,3]
     ["aa",3,3]]

a2 = [["sdsd",1,3]
     ["sdsd",6,0]
     ["sdsd",2,5]]

a3 = [["fffffff",1,3]]

That is, according to the first value of each list. I need to do this for a list of lists with thousands of elements... How can I do it efficiently?

Upvotes: 1

Views: 1977

Answers (4)

inspectorG4dget
inspectorG4dget

Reputation: 113955

You're better off making a dictionary. If you really want to make a bunch of variables, you'll have to use globals(), which isn't really recommended.

a = [["aa",1,3]
     ["aa",3,3]
     ["sdsd",1,3]
     ["sdsd",6,0]
     ["sdsd",2,5]
     ["fffffff",1,3]]

d = {}
for sub in a:
    key = sub[0]
    if key not in d: d[key] = []
    d[key].append(sub)

OR

import collections

d = collections.defaultdict(list)
for sub in a:
    d[sub[0]].append(sub)

Upvotes: 4

hilberts_drinking_problem
hilberts_drinking_problem

Reputation: 11602

If input is sorted on first element:

from itertools import groupby
from operator import itemgetter

a = [["aa",1,3],
     ["aa",3,3],
     ["sdsd",1,3],
     ["sdsd",6,0],
     ["sdsd",2,5],
     ["fffffff",1,3]]

b = { k : list(v) for k, v in groupby(a, itemgetter(0))}

Upvotes: 1

Garrett R
Garrett R

Reputation: 2662

A defaultdict will work nicely here:

a = [["aa",1,3],
["aa",3,3],
["sdsd",1,3],
["sdsd",6,0],
["sdsd",2,5],
["fffffff",1,3]]
from collections import defaultdict
d = defaultdict(list)
for thing in a:
    d[thing[0]] += thing,

for separate_list in d.values():
    print separate_list

Output

[['aa', 1, 3], ['aa', 3, 3]]
[['sdsd', 1, 3], ['sdsd', 6, 0], ['sdsd', 2, 5]]
[['fffffff', 1, 3]]

Upvotes: 0

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

Create a dictionary with the first element as key and matching lists as value. And you will get a dictionary where value of each key value pair will be group of lists having same first element. For example,

a = [["aa", 1, 3],
     ["aa", 3, 3],
     ["sdsd", 1, 3],
     ["sdsd", 6, 0],
     ["sdsd", 2, 5],
     ["fffffff", 1, 3]]
d = {}
for e in a:
    d[e[0]] = d.get(e[0]) or []
    d[e[0]].append(e)

And now you can simply get the lists seperately,

a1 = d['aa']
a2 = d['sdsd']

Upvotes: 0

Related Questions