如何在Python中找到恰好发生次数为2的列表元素的索引
我试图编写一个代码,返回列表中元素的所有索引,这些索引重复两次。我自己的算法有问题。我的代码只返回它找到的第一个匹配项。我想把这个修好。这是我自己的代码(我知道这有点奇怪): 我感谢任何人的帮助。提前感谢。试试这个:如何在Python中找到恰好发生次数为2的列表元素的索引,python,python-3.x,list,dictionary,find-occurrences,Python,Python 3.x,List,Dictionary,Find Occurrences,我试图编写一个代码,返回列表中元素的所有索引,这些索引重复两次。我自己的算法有问题。我的代码只返回它找到的第一个匹配项。我想把这个修好。这是我自己的代码(我知道这有点奇怪): 我感谢任何人的帮助。提前感谢。试试这个: from collections import Counter userInput = input().split() counter = Counter(userInput) print([x[0] for x in counter.items() if x[1] == 2])
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]
如果不允许使用库,则可以不使用计数器(尽管运行速度较慢):
就这样!谢谢谢谢谢谢!!:)轻微改进(在可读性和性能方面):
[val for val,cnt in counter.items(),如果cnt==2]
。使用名称可以使其更清晰,并且解包到名称并读取本地名称比重复索引(至少在CPython引用解释器上)更有效。另外,userInput
应该是map(int,input().split())
或者(如果仍然需要list
)[int(x)for x in input().split()]
以匹配OP的类型转换。为什么要解压缩到值
,然后忽略它并使用引用[键]
?你已经有了值
,你不需要再查一遍吗?如果你还是要查找它,.items()
没有任何作用。你完全正确。。。
>>> 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]