Python 字典分类列表中的列表

180 阅读2分钟

我们有一个嵌套列表,其中包含若干个子列表,每个子列表代表一个记录,记录包含四个元素:URL、名称、日期和类别。我们需要将这些记录按类别进行分类,并创建一个字典,其中键是类别,值是一个包含该类别所有记录的列表。

huake_00257_.jpg 2、解决方案

我们可以使用几个不同的方法来解决这个问题。

  • 方法一:使用 itertools.groupby

itertools.groupby 是 Python 中的一个内置函数,用于对可迭代对象进行分组。我们可以使用它来将列表中的列表按类别进行分组。

import itertools
import operator

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"]
]

# 对列表中的列表按类别进行分组
groups = itertools.groupby(l, operator.itemgetter(3))

# 创建一个字典,其中键是类别,值是该类别所有记录的列表
result = dict((category, list(l)) for category, l in groups)

print(result)

输出:

{'one category': [['hello', 'world', '2010', 'one category'], ['asdfasdf', 'adfasdf', '2010', 'one category']], 'another category': [['foo', 'bar', '2010', 'another category'], ['qwer', 'req', '2010', 'another category']]}
  • 方法二:使用 defaultdict

collections.defaultdict 是 Python 中的一个内置类,用于创建字典。当我们向 defaultdict 中添加一个不存在的键时,它会自动创建一个新的键,并将其值初始化为空列表。我们可以使用它来将列表中的列表按类别进行分组。

import collections

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"]
]

# 创建一个 defaultdict,其中键是类别,值是该类别所有记录的列表
result = collections.defaultdict(list)

# 将列表中的列表按类别添加到 defaultdict 中
for entry in l:
    result[entry[3]].append(entry)

print(result)

输出:

defaultdict(<class 'list'>, {'one category': [['hello', 'world', '2010', 'one category'], ['asdfasdf', 'adfasdf', '2010', 'one category']], 'another category': [['foo', 'bar', '2010', 'another category'], ['qwer', 'req', '2010', 'another category']]})
  • 方法三:使用 setdefault

dict.setdefault 是 Python 中的一个内置方法,用于在字典中添加一个键。如果键不存在,它会创建一个新的键,并将其值初始化为空列表。如果键存在,它会返回该键对应的值。我们可以使用它来将列表中的列表按类别进行分组。

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"]
]

# 创建一个字典,其中键是类别,值是该类别所有记录的列表
result = {}

# 将列表中的列表按类别添加到字典中
for e in l:
    result.setdefault(e[3], []).append(e)

print(result)

输出:

{'one category': [['hello', 'world', '2010', 'one category'], ['asdfasdf', 'adfasdf', '2010', 'one category']], 'another category': [['foo', 'bar', '2010', 'another category'], ['qwer', 'req', '2010', 'another category']]}