微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何查找在 Python 中恰好出现 2 次的列表元素的索引 如果您正在寻找索引,这应该有效

如何解决如何查找在 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])
,

如果您正在寻找索引,这应该有效


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 并在列表理解中进行枚举:

#if

如果你不被允许使用库,你可以不用 Counter 来实现(虽然它会运行得更慢):

#ifdef

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。