Python - 列表中两个元素之间最近的出现
给定一个列表和两个元素, x和y从元素y中找到元素x的最近出现索引。
Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 4, y = 6
Output : 1
Explanation : 4 is found at 1, 12 and 14th index, 6 is at 5th index, nearest is 1st index.
Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 7, y = 6
Output : 3
Explanation : 7 is found at 3rd and 8th index, 6 is at 5th index, nearest is 3rd index.
方法:使用列表理解 + 循环 + 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))
输出:
The original list is : [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4]
Minimum distance index: 8