列表的示例列表:
[
["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" : [["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"]]}
最佳答案
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)))
关于python - 在python中按1个元素对列表列表进行分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2092380/