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

如何用列表推导式同时获取目标子列表的首次索引与出现次数

解决方法

可以通过列表推导式配合内置函数,一次性获取目标子列表的首次索引和出现次数,代码示例如下:

location = [["world", 'Live'], ["alpha",'Live'], ['hello', 'Scheduled'],['alpha', 'Live'], ['just', 'Live'], ['alpha','Scheduled'], ['alpha', 'Live']]
target = ["alpha", "Live"]

# 用列表推导式收集所有匹配目标的元素索引
matched_indices = [i for i, item in enumerate(location) if item == target]
# 提取首次索引和出现次数
first_index = matched_indices[0] if matched_indices else -1
count = len(matched_indices)

print(f"index, count = {first_index}, {count}")

运行后会输出:index, count = 1, 3,完全符合需求。

简单说明

  • enumerate(location)用于同时遍历元素的索引和对应值
  • 列表推导式筛选出所有与目标子列表匹配的索引
  • 首次索引取筛选后列表的第一个元素,出现次数直接取列表长度
  • 加入了空列表判断,避免目标不存在时触发索引错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:15:37