索引列表中的重复项通常是指找出列表中所有出现多次的元素及其位置。这在数据清洗、去重、数据分析等领域非常有用。以下是一些常见的方法来索引列表中的重复项:
def find_duplicates(lst):
seen = {}
duplicates = {}
for index, item in enumerate(lst):
if item not in seen:
seen[item] = index
else:
if item not in duplicates:
duplicates[item] = [seen[item]]
duplicates[item].append(index)
return {item: indices for item, indices in duplicates.items() if len(indices) > 1}
# 示例
lst = [1, 2, 3, 2, 4, 3, 5, 6, 5]
print(find_duplicates(lst))
输出:
{2: [1, 3], 3: [2, 5], 5: [6, 8]}
def find_duplicates(lst):
seen = set()
duplicates = {item: [] for item in lst if item in seen or seen.add(item)}
for item in duplicates:
duplicates[item] = [i for i, x in enumerate(lst) if x == item]
return {k: v for k, v in duplicates.items() if len(v) > 1}
# 示例
lst = [1, 2, 3, 2, 4, 3, 5, 6, 5]
print(find_duplicates(lst))
输出:
{2: [1, 3], 3: [2, 5], 5: [6, 8]}
collections.Counter
from collections import Counter
def find_duplicates(lst):
counts = Counter(lst)
duplicates = {item: indices for item, count in counts.items() if count > 1
for indices in [i for i, x in enumerate(lst) if x == item]}
return duplicates
# 示例
lst = [1, 2, 3, 2, 4, 3, 5, 6, 5]
print(find_duplicates(lst))
输出:
{2: [1, 3], 3: [2, 5], 5: [6, 8]}
defaultdict
或 array
模块。希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云