在python中按列表分类列表

时间:2010-01-19 09:22:44

标签: python list dictionary map sorting

列表的示例列表:

[
["url","name","date","category"]
["hello","world","2010","one category"]
["foo","bar","2010","another category"]
["asdfasdf","adfasdf","2010","one category"]
["qwer","req","2010","another category"]
]

我希望做的是创建字典 - > category:[条目列表]。

结果字典将是:

{"category" : [["url","name","date","category"]],
"one category" : [["hello","world","2010","one category"],["asdfasdf","adfasdf","2010","one category"]],
"another category" : [["foo","bar","2010","another category"], ["qwer","req","2010","another category"]]}

6 个答案:

答案 0 :(得分:7)

dict((category, list(l)) for category, l 
     in itertools.groupby(l, operator.itemgetter(3))

这里最重要的是使用itertools.groupby。它只是返回迭代而不是列表,这就是为什么要调用list(l),这意味着如果你对它好,你可以简单地写dict(itertools.groupby(l, operator.itemgetter(3)))

答案 1 :(得分:5)

newdict = collections.defaultdict(list)
for entry in biglist:
  newdict[entry[3]].append(entry)

答案 2 :(得分:2)

ghostdog74的答案变体,完全使用了setdefaults的语义:

result={}
for li in list_of_lists:
    result.setdefault(li[-1], []).append(li)

答案 3 :(得分:1)

list_of_lists=[
["url","name","date","category"],
["hello","world","2010","one category"],
["foo","bar","2010","another category"],
["asdfasdf","adfasdf","2010","one category"],
["qwer","req","2010","another category"]
]
d={}
for li in list_of_lists:
    d.setdefault(li[-1], [])
    d[ li[-1] ].append(li)
for i,j in d.iteritems():
    print i,j

答案 4 :(得分:1)


d = {}
for e in l:
    if e[3] in d:
        d[e[3]].append(e)
    else:
        d[e[3]] = [e]

答案 5 :(得分:-2)

>>> l = [
... ["url","name","date","category"],
... ["hello","world","2010","one category"],
... ["foo","bar","2010","another category"],
... ["asdfasdf","adfasdf","2010","one category"],
... ["qwer","req","2010","another category"],
... ]
#Intermediate list to generate a more dictionary oriented data
>>> dl = [ (li[3],li[:3]) for li in l ]
>>> dl
[('category', ['url', 'name', 'date']), 
 ('one category', ['hello', 'world', '2010']), 
 ('another category', ['foo', 'bar', '2010']), 
 ('one category', ['asdfasdf', 'adfasdf', '2010']), 
 ('another category', ['qwer', 'req', '2010'])]
#Final dictionary
>>> d = {}
>>> for cat, data in dl:
...   if cat in d:
...     d[cat] = d[cat] + [ data ]
...   else:
...     d[cat] = [ data ]
...
>>> d
{'category': [['url', 'name', 'date']], 
 'one category': [['hello', 'world', '2010'], ['asdfasdf', 'adfasdf', '2010']], 
 'another category': [['foo', 'bar', '2010'], ['qwer', 'req', '2010']]}

最终数据有点不同,因为我没有在数据中包含该类别(对我来说似乎毫无意义),但如果需要,您可以轻松添加...