如何在Python中按列表元素值将对应索引分组生成集合?
解决Python中按列表元素值分组索引的问题
嘿,这个需求实现起来挺简单的,我给你两种常用的思路,都能轻松得到你想要的结果:
方法1:手动遍历构建字典
这是最直观的方式,适合刚接触Python的朋友理解:
y = [0,2,1,2,1,1,2,1] # 初始化一个空字典,键存列表的元素值,值存对应索引的集合 index_groups = {} # 用enumerate同时获取索引和元素值 for idx, value in enumerate(y): # 如果当前值还没在字典里,先创建一个空集合 if value not in index_groups: index_groups[value] = set() # 把索引添加到对应值的集合中 index_groups[value].add(idx) # 提取你需要的集合 s1 = index_groups[0] s2 = index_groups[2] s3 = index_groups[1] # 输出结果 print(f"s1={s1}、s2={s2}、s3={s3}")
方法2:用collections.defaultdict简化代码
如果想让代码更简洁,可以用Python标准库的defaultdict,它能自动帮我们处理键不存在的情况:
from collections import defaultdict y = [0,2,1,2,1,1,2,1] # 直接创建一个默认值为集合的字典 index_groups = defaultdict(set) for idx, value in enumerate(y): # 不用判断键是否存在,直接添加索引就行 index_groups[value].add(idx) # 同样提取集合 s1 = index_groups[0] s2 = index_groups[2] s3 = index_groups[1] print(f"s1={s1}、s2={s2}、s3={s3}")
两种方法运行后都会输出:s1={0}、s2={1, 3, 6}、s3={2, 4, 5, 7},完全符合你的需求。
另外提一句:如果之后你的列表元素值有变化,用字典存储的方式会比单独定义s1、s2、s3更灵活,直接通过键就能获取对应索引集合~
内容的提问来源于stack exchange,提问作者aizan zafar
相关产品推荐
相关产品推荐

