用Python按一个元素对列表的列表进行分类
这是一个包含多个列表的例子:
[
["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"]]}
6 个回答
2
这是对ghostdog74回答的一种变体,充分利用了setdefaults的语义:
result={}
for li in list_of_lists:
result.setdefault(li[-1], []).append(li)
5
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在程序中使用它。这个过程就像是从冰箱里拿食材,然后用这些食材做饭。
当我们在编写代码时,可能会遇到一些问题,比如数据格式不对,或者程序运行时出错。这就像是你在做饭时,发现食材不新鲜,或者忘记加盐一样。
为了让程序顺利运行,我们需要仔细检查每一步,确保数据是正确的,程序逻辑是合理的。这样才能做出美味的菜肴,也就是让程序正常工作。
总之,编程就像做饭,需要耐心和细心,才能做出让人满意的结果。
newdict = collections.defaultdict(list)
for entry in biglist:
newdict[entry[3]].append(entry)
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)))
。