首页 > 解决方案 > 如何在Python中找到恰好出现2的列表元素的索引

问题描述

我正在尝试编写一个代码,它返回列表中元素的所有索引,这些索引重复两次。我自己的算法有问题。我的代码只返回它找到的第一个事件。我想解决这个问题。这是我自己的代码(我知道这有点奇怪):

from collections import Counter 

length = int(input())
user_input = [int(x) for x in input().split()]
occurrances = Counter(user_input)
check_list = []
check_list.append(list(occurrances.keys())[list(occurrances.values()).index(2)])
print(check_list)

我感谢任何人的帮助。提前致谢。

标签: pythonpython-3.xlistdictionaryfind-occurrences

解决方案


试试这个:

from collections import Counter

userInput = input().split()
counter = Counter(userInput)
print([x[0] for x in counter.items() if x[1] == 2])

推荐阅读