1

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?

1
  • what is "efficient"? Why is iterating through all entries of the original list not efficient? Commented Mar 22, 2016 at 0:50

4 Answers 4

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

@zondo: I had a huge error in there. Fixed. Thanks :)
1

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))}

Comments

0

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']

Comments

0

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.