You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中统计列表条目包含另一列表单词的数量

问题描述

我有两个列表:

  • List1的每个条目是一段文本,示例:
List1 = ["My house is red", "The dog is black", "The table is small", "The wind is cold"]
  • List2的每个条目是单个单词,示例:
List2 = ["house", "red", "wind", "small", "big", "dog", "cat", "fox", "car"]

需要统计List1中每个文本条目包含多少个List2里的单词,期望得到结果列表:

[2, 1, 1, 1]

尝试过List1.count(List2),但该方法仅接受单个值;也写了for循环但逻辑存在问题:

List 3 = []

for w in List2:
    if w in List1:
      List3 = 1
    else:
      List3 = List3[w] + 1

寻求正确的实现方案。


解决方案

方法1:基础嵌套循环

遍历List1的每个句子,拆分句子为单词后,逐个检查是否在List2中,统计符合条件的数量:

List1 = ["My house is red", "The dog is black", "The table is small", "The wind is cold"]
List2 = ["house", "red", "wind", "small", "big", "dog", "cat", "fox", "car"]

List3 = []
for sentence in List1:
    # 按空格拆分句子为单词(若句子含标点,可先做清洗,比如用strip()去除标点)
    words = sentence.split()
    match_count = 0
    for word in words:
        if word in List2:
            match_count += 1
    List3.append(match_count)

print(List3)  # 输出: [2, 1, 1, 1]

方法2:高效集合查询(推荐)

把List2转为集合,集合的成员查询效率远高于列表(O(1) vs O(n)),适合List2元素较多的场景,再结合生成器表达式简化代码:

List1 = ["My house is red", "The dog is black", "The table is small", "The wind is cold"]
# 转List2为集合
List2_set = {"house", "red", "wind", "small", "big", "dog", "cat", "fox", "car"}

List3 = []
for sentence in List1:
    words = sentence.split()
    # 用生成器统计符合条件的单词数
    match_count = sum(1 for word in words if word in List2_set)
    List3.append(match_count)

print(List3)  # 输出: [2, 1, 1, 1]

方法3:列表推导式(极简写法)

将上述逻辑压缩为一行列表推导式,更简洁:

List1 = ["My house is red", "The dog is black", "The table is small", "The wind is cold"]
List2_set = {"house", "red", "wind", "small", "big", "dog", "cat", "fox", "car"}

List3 = [sum(1 for word in sentence.split() if word in List2_set) for sentence in List1]
print(List3)  # 输出: [2, 1, 1, 1]

原代码问题说明

你之前的循环逻辑存在多处错误:

  1. 遍历对象错误:应该遍历List1的句子,而非List2的单词
  2. 列表操作错误:List3被错误赋值为整数,正确做法是用append()向列表添加元素
  3. 索引错误:List3[w]试图用单词作为列表索引,这不符合列表的索引规则(列表只能用整数索引)

内容的提问来源于stack exchange,提问作者Ruslan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 14:28:41