如何在 Python 中查找恰好出现 2 次的列表元素的索引
How to find index of elements of a list that have occurrance of exactly 2 in Python
我正在尝试编写一个代码,其中 returns 列表中元素的所有索引,这些索引重复了两次。我自己的算法有问题。我的代码仅 returns 它找到的第一个事件。我想要这个固定。这是我自己的代码(我知道这有点奇怪):
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])
如果您要查找索引,这应该有用
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)
查找出现两次的项目的索引。
>>> 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 并在列表推导中枚举:
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]
我正在尝试编写一个代码,其中 returns 列表中元素的所有索引,这些索引重复了两次。我自己的算法有问题。我的代码仅 returns 它找到的第一个事件。我想要这个固定。这是我自己的代码(我知道这有点奇怪):
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])
如果您要查找索引,这应该有用
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)
查找出现两次的项目的索引。
>>> 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 并在列表推导中枚举:
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]