如何在Python中找到恰好发生次数为2的列表元素的索引

2024-06-25 07:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个代码,返回列表中元素的所有索引,这些索引重复两次。我自己的算法有问题。我的代码只返回它找到的第一个匹配项。我想把这个修好。这是我自己的代码(我知道这有点奇怪):

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)

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


Tags: 代码fromimport算法元素列表inputcheck
3条回答

试试这个:

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

要获取索引,可以在列表中使用计数器和枚举:

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] 

如果不允许使用库,则可以不使用计数器(尽管运行速度较慢):

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

相关问题 更多 >