📜  Python - 列表中两个元素之间最近的出现

📅  最后修改于: 2022-05-13 01:55:16.928000             🧑  作者: Mango

Python - 列表中两个元素之间最近的出现

给定一个列表和两个元素, xy从元素y中找到元素x的最近出现索引。

方法:使用列表理解 + 循环 + index()

在这里,我们使用列表推导找到y的所有索引,然后使用index()获取x的索引,在该循环用于获取索引差异后,返回最近的索引作为结果。

Python3
# Python3 code to demonstrate working of
# Nearest occurrence of x from y in List
# Using list comprehension + loop + index()
 
 
# function to find index of nearest
# occurrence between two elements
def nearestOccurrenceIndex(test_list, x, y):
 
    # checking if both elements are present in list
    if x not in test_list or y not in test_list:
        return -1
    # getting indices of x
    x_idx = [idx for idx in range(len(test_list)) if test_list[idx] == x]
 
    # getting y index
    y_idx = test_list.index(y)
 
    # getting min_dist index
    min_dist = 1000000
    res = None
    for ele in x_idx:
 
        # checking for min ele, and updating index
        if abs(ele - y_idx) < min_dist:
            res = ele
            min_dist = abs(ele - y_idx)
    return res
 
 
# initializing list
input_list = [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4]
 
# printing original list
print("The original list is : " + str(input_list))
 
# initializing x
x = 4
 
# initializing y
y = 6
 
# printing result
print("Minimum distance index: ", nearestOccurrenceIndex(input_list, x, y))


输出: