gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:27 27 4
gpt4 key购买 nike

列表的示例列表:

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com