[英]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. 如果您确实想创建一堆变量,则必须使用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)
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: 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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.