gpt4 book ai didi

python - 计算嵌套列表中的字符串

转载 作者:行者123 更新时间:2023-12-04 06:52:23 25 4
gpt4 key购买 nike

我有一个列表列表如下。

sentences = [
["my", "first", "question", "in", "stackoverflow", "is", "my", "favorite"],
["my", "favorite", "language", "is", "python"]
]

我想获取 sentences 中每个单词的数量列表。所以,我的输出应该如下所示。
{
'stackoverflow': 1,
'question': 1,
'is': 2,
'language': 1,
'first': 1,
'in': 1,
'favorite': 2,
'python': 1,
'my': 3
}

我目前正在这样做。
frequency_input = [item for sublist in sentences for item in sublist]
frequency_output = dict(
(x,frequency_input.count(x))
for x in set(frequency_input)
)

但是,对于长列表,它根本没有效率。我有一个很长的列表,列表中有大约 100 万个句子。我花了两天时间运行它,它仍在运行。

在这种情况下,我想让我的程序更有效率。我当前的第一行代码是 O(n^2)我的第二行是 O(n) .请让我知道在 python 中是否有更有效的方法。如果我能用比现在更短的时间运行它,那将是非常理想的。我不担心空间复杂性。

如果需要,我很乐意提供更多详细信息。

最佳答案

一种更简单、更高效的方法是使用 itertools.chain 来展平列表。 , 并用 collections.Counter 计算字符串:

from collections import Counter
from itertools import chain

Counter(chain.from_iterable(sentences))

Counter({'my': 3,
'first': 1,
'question': 1,
'in': 1,
'stackoverflow': 1,
'is': 2,
'favorite': 2,
'language': 1,
'python': 1})

关于python - 计算嵌套列表中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57817905/

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