Python如何获取列表中仅出现一次元素的所有索引?
获取列表中出现次数不超过一次的元素的索引
这儿有几种实用的方案可以满足你的需求,针对你的示例列表example = [0,1,1,2,3,3,4],都能得到目标索引列表[0,3,6]:
方法一:用collections.Counter(推荐,高效)
利用Python标准库的Counter先统计每个元素的出现频次,再遍历原列表筛选符合条件的索引:
from collections import Counter example = [0,1,1,2,3,3,4] # 统计每个元素的出现次数 element_counts = Counter(example) # 筛选出出现次数<=1的元素的索引 desired_index_list = [idx for idx, num in enumerate(example) if element_counts[num] <= 1] print(desired_index_list) # 输出: [0, 3, 6]
这个方法的时间复杂度是O(n),处理大列表也很高效。
方法二:用numpy实现(适合数值型列表)
如果你习惯用numpy,可以结合np.bincount和np.isin来完成:
import numpy as np example = np.array([0,1,1,2,3,3,4]) # 统计每个非负整数元素的出现次数 counts = np.bincount(example) # 找出出现次数<=1的元素 target_elements = np.where(counts <= 1)[0] # 获取这些元素在原数组中的索引并转成列表 desired_index_list = np.where(np.isin(example, target_elements))[0].tolist() print(desired_index_list) # 输出: [0, 3, 6]
如果你的列表包含负数或非整数类型,可以改用np.unique配合return_counts=True来统计频次:
import numpy as np example = np.array([0,1,1,2,3,3,4]) elements, counts = np.unique(example, return_counts=True) target_elements = elements[counts <= 1] desired_index_list = np.where(np.isin(example, target_elements))[0].tolist()
方法三:纯原生Python(无需额外库,适合小列表)
如果不想导入任何库,可以直接用列表的count方法,但这种方法时间复杂度是O(n²),大列表会比较慢:
example = [0,1,1,2,3,3,4] desired_index_list = [] for idx, num in enumerate(example): if example.count(num) <= 1: desired_index_list.append(idx) print(desired_index_list) # 输出: [0, 3, 6]
内容的提问来源于stack exchange,提问作者till Kadabra
相关产品推荐
相关产品推荐

