Python 在给出起始位置但向后的列表中查找第一个重合点的索引

Python 在给出起始位置但向后的列表中查找第一个重合点的索引,python,Python,在给定索引之前,是否有任何类似于蟒蛇的方法来发现第一个巧合 例如,我想找到在1之前的2,以及在1之后的2 a = [0,2,0,0,1,0,0,2,0] 对于1后面的2,我使用这个a.index(2,4) 有什么简单或干净的方法吗?您可以反转列表并计算反转列表中“枢轴”元素的索引,然后像往常一样使用索引: def find_before(lst, e, idx): new_idx = len(lst) - idx - 1 return len(lst) - lst[::-1].

在给定索引之前,是否有任何类似于蟒蛇的方法来发现第一个巧合

例如,我想找到在
1
之前的
2
,以及在
1
之后的
2

a = [0,2,0,0,1,0,0,2,0]
对于1后面的
2
,我使用这个
a.index(2,4)


有什么简单或干净的方法吗?

您可以反转列表并计算反转列表中“枢轴”元素的索引,然后像往常一样使用
索引:

def find_before(lst, e, idx):
    new_idx = len(lst) - idx - 1
    return len(lst) - lst[::-1].index(e, new_idx) - 1
值得注意的是,对于大型列表来说,这是一个坏主意,因为它在反转时会临时创建一个副本。对于这种情况,一个更好的想法是blhsing所做的,这只是在列表中后退:

def find_before(lst, e, idx):
    i = idx
    while i > 0:
        i -= 1
        if lst[i] == e:
        return i
    else:
        raise ValueError(f"No element {e} found before index {idx}")

您只需自己完成,因为对于列表,没有内置的函数与
str.rindex
等效:

def rindex(lst, x, start=-1, end=0):
    if start < 0:
        start += len(lst)
    i = start
    while i >= end and lst[i] != x:
        i -= 1
    if i < 0:
        raise ValueError()
    return i

a = [0,2,0,0,1,0,0,2,0]
print(rindex(a, 2, 4))
在O(n)中,您可以构建一个保存列表中任何元素的所有位置的
dict

a = [0,2,0,0,1,0,0,2,0]

pos = {}

for idx, elem in  enumerate(a):
    pos.setdefault(elem,set())
    pos[elem].add(idx)    

print(pos) # {0: {0, 2, 3, 5, 6, 8}, 2: {1, 7}, 1: {4}}
查找一个元件的位置只需一个O(1)操作:

print(pos[2])  # {1,7}
如果您想要第一次和最后一次出现,可以执行以下操作:

print(min(pos[0]),max(pos[0])  #  0 8
您还可以查询其他内容:

# get index of first 2 that is before the 1st 1
print( min(x for x in pos[2] if x < min(pos[1])))  # 1

# get index of all 0s that are after the 1st 1
print( list(x for x in pos[0] if x > min(pos[1])))  # [5, 6, 8]

您可以使用
min/max
将列表缩减为1个元素。

答案可以分解为三个子操作:将数组拆分为两个子数组,然后从末尾搜索第一个子数组,从开头搜索第二个子数组

def index(array, value, pivot):

    def find(array):
        return array.index(value)

    first_half = arr[ (pivot - 1) : : -1 ]
    last_half = arr[ (pivot + 1) : ]
    return [ pivot - find(first_half) - 1, pivot + find(last_half) + 1 ]
本质上,此方法围绕
pivot
拆分数组,并向后重新排列第一个子数组。在这之后,您只需在这两者中找到第一个出现的
value
,它对应于数组中最近出现的
value
pivot
。它的工作原理如下:

indexes = index(array, 2, 4)
# [1, 7]

你想在左边找到离1最近的2个,在右边找到离1最近的2个吗?@ThatBird是的,举个例子:
2 before 1st 1: [1]
2 after  1st 1: [7]
def index(array, value, pivot):

    def find(array):
        return array.index(value)

    first_half = arr[ (pivot - 1) : : -1 ]
    last_half = arr[ (pivot + 1) : ]
    return [ pivot - find(first_half) - 1, pivot + find(last_half) + 1 ]
indexes = index(array, 2, 4)
# [1, 7]