简体   繁体   中英

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?

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)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM