Skip to main content
 首页 » 编程设计

python之在python中按1个元素对列表列表进行分类

2025年05月04日8bhlsheji

列表的示例列表:

[ 
["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)))