如何用列表推导式同时获取目标子列表的首次索引与出现次数
解决方法
可以通过列表推导式配合内置函数,一次性获取目标子列表的首次索引和出现次数,代码示例如下:
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
相关产品推荐
相关产品推荐

