在Python中查找列表中恰好出现两次的元素及其索引,可以通过以下步骤实现:
[1, 2, 3, 2, 4, 3]
{'1': 1, '2': 2, '3': 2, '4': 1}
def find_elements_appear_twice(lst):
# 统计每个元素的出现次数
count_dict = {}
for element in lst:
if element in count_dict:
count_dict[element] += 1
else:
count_dict[element] = 1
# 找出恰好出现两次的元素及其索引
result = {}
for element, count in count_dict.items():
if count == 2:
result[element] = [i for i, x in enumerate(lst) if x == element]
return result
# 示例列表
lst = [1, 2, 3, 2, 4, 3]
result = find_elements_appear_twice(lst)
print(result)
count_dict
统计每个元素在列表中的出现次数。{2: [1, 3], 3: [2, 5]}
通过上述方法,你可以高效地找到列表中恰好出现两次的元素及其索引。
领取专属 10元无门槛券
手把手带您无忧上云