如何在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)
我感谢任何人的帮助。提前谢谢。

试试这个:

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

查找出现两次的项的索引。

>>> L = [1,2,3,1,4,6,6]
>>> from collections import Counter
>>> c = Counter(L)
>>> for key in filter(lambda x: c[x] == 2, c):
one = L.index(key)
two = L.index(key, one+1)
print(key, 'found at indexes', ' '.join(map(str, [one, two])))

1 found at indexes 0 3
6 found at indexes 5 6

要获取索引,可以在列表推导式中使用Counter和enumerate:

from collections import Counter
L  = [1,2,3,4,3,4,2,3,5]
L2 = [i for c in [Counter(L)] for i,v in enumerate(L) if c[v]==2]
print(L2)
[1, 3, 5, 6] 

如果你不被允许使用库,你可以不使用Counter(尽管它会运行得更慢):

L2 = [i for i,v in enumerate(L) if L.count(v)==2]

如果您正在查找索引


from collections import Counter 
user_input = [int(x) for x in input().split()]
occurrences = Counter(user_input)
keys = [key for key in occurrences.keys() if occurrences[key]==2 ]
check_list = [x for x in range(len(user_input)) if user_input[x] in keys]
print(check_list)

相关内容

  • 没有找到相关文章

最新更新