Python - 按值拆分列表

时间:2016-03-22 00:45:29

标签: python list

我想拆分以下列表列表

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

进入以下三个清单列表:

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

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

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

即,根据每个列表的第一个值。我需要为包含数千个元素的列表列表执行此操作...如何有效地执行此操作?

4 个答案:

答案 0 :(得分:3)

你最好做一本字典。如果你真的想要制作一堆变量,你将不得不使用globals(),这不是真正推荐的。

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)

答案 1 :(得分:1)

如果输入在第一个元素上排序:

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

答案 2 :(得分:0)

创建一个字典,第一个元素作为键,匹配列表作为值。并且您将获得一个字典,其中每个键值对的值将是具有相同第一元素的列表组。例如,

sort

现在你可以单独获取列表,

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)

答案 3 :(得分:0)

defaultdict在这里可以很好地工作:

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

输出

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