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

Python:当另一列表满足条件时,统计目标列表符合要求的元素数量

列表位置统计问题解决方案

问题说明

给定两个列表:

list1 = [3, 26, 17, 7, 35, 8, 14, 24]
list2 = ["long", "long", "long", "short", "short", "short", "short", "short"]

需要统计同时满足以下两个条件的位置数量:

  • list1对应位置的元素大于10
  • list2对应位置的元素为**"short"**

预期输出为3,对应list1中索引4、6、7的元素35、14、24,这些位置的list2元素均为"short"。

解决方案

方法1:生成器表达式 + sum()

这是最简洁的Pythonic写法,用zip()同时遍历两个列表,生成器筛选符合条件的项,sum()直接统计数量:

count = sum(1 for num, category in zip(list1, list2) if num > 10 and category == "short")
print(count)  # 输出:3

方法2:循环遍历计数

如果需要更直观的执行过程,用循环逐个检查每个位置:

count = 0
for idx in range(len(list1)):
    if list1[idx] > 10 and list2[idx] == "short":
        count += 1
print(count)  # 输出:3

方法3:numpy 高效处理(适合大型数据集)

如果处理的是大规模数据,使用numpy的向量化操作会更高效:

import numpy as np

arr1 = np.array(list1)
arr2 = np.array(list2)
count = np.sum((arr1 > 10) & (arr2 == "short"))
print(count)  # 输出:3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:55:59