Py学习  »  Python

在Python中查找n个元素相等的索引

Richard Johansson • 3 年前 • 1151 次点击  

首先,如果其他地方已经回答了这个问题,我很抱歉。但我一直在努力解决这个问题,我想在哪里得到索引 N 元素会自我重复。例如,如果我想从一个包含布尔的列表中得到索引 True 重复了三次:

A = [False, False, True, True, True, False, True, True, True]

所以在这个例子中,我想要索引2。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/128576
 
1151 次点击  
文章 [ 4 ]  |  最新文章 3 年前
Dharman Khoisan25
Reply   •   1 楼
Dharman Khoisan25    3 年前

这是另一种方法。

def get_index(lst, n):
    for i in range(len(lst)):
        if lst[i:i+n] == [True]*n:
            return i
    return -1

用法基本上是 print(get_index(lst, 3)) 如果找到,则返回索引,否则返回-1。 你当然可以修改 True 成为你想要匹配的任何值。

Alex R
Reply   •   2 楼
Alex R    3 年前

如果当前元素等于上一个元素,则可以迭代列表并增加计数器。如果你的柜台 n ,您可以轻松计算指数:

def find(lst, n: int):
    counter = 1
    previous = None

    for index, element in enumerate(lst):
        if element == previous:
            counter += 1
        else:
            counter = 1

        if counter == n:
            return index - n + 1

        previous = element

    return -1

输出:

A = [False, False, True, True, True, False, True, True, True]
print(find(A, 3))

-> 2
Arthur King
Reply   •   3 楼
Arthur King    3 年前

有很多方法可以做到这一点。这里有一个:

A = [False, False, True, True, True, False, True, True, True]

def findSequence(lst, v, n):
    offset = 0
    while offset < len(lst) - n:
        try:
            i = lst[offset:].index(v)
            offset += i
            if lst[offset:offset+n].count(v) == n:
                return offset
            offset += 1
        except IndexError:
            break


print(findSequence(A, True, 3))

输出:

2
Tamir
Reply   •   4 楼
Tamir    3 年前

一个简单的解决方案:

编辑 :已更改为支持 n 价值观

res = list()
for index, value in enumerate(A):
    if index == len(A)-n:
        break
    if all([val==value for val in A[index:index+n]]):
        res.append(index)