如何从列表中查找多个值的索引



我有一个长度为100的值列表,我想知道如何在python列表中获得它们的索引。例如:

target_values = [0,0.001,0.002,0.003,..., 0.01]
len(target_values) = 100
list = [0,0.0005,0.001, 0.0015, 0.002,...., 0.1]
len(list) = 1747
Output_index = [0,2,4,..., n]
len(Output_index) = 100 #should be 100

有办法找到它吗?

您可以遍历目标值并使用index()

在大列表中找到它们
target_values = [0,0.001,0.002,0.003,..., 0.01]
large_list = [0,0.0005,0.001, 0.0015, 0.002,...., 0.1]
output_index = []
for value in target_values:
output_index.append(large_list.index(value))

index()函数执行此操作。请注意,如果列表中有重复项,则可能无法正常工作。

不要使用list作为变量名。它将显示类型list

target_values = [0,0.001,0.002,0.003,..., 0.01]
larger_list = [0,0.0005,0.001, 0.0015, 0.002,...., 0.1]
Output_index = []
for value in target_values:
try:
Output_index.append(larger_list.index(value))
except ValueError:
# value not found in larger list, handle it
pass

与@Victor的答案类似,但具有列表推导式,并且仅在目标值不在列表中时返回None

target_values = [0,0.001,0.002, 0.003, 0.01]
large_list = [0,0.0005,0.001, 0.0015, 0.002, 0.1]
output_index = [large_list.index(target_value) 
if target_value in large_list 
else None 
for target_value in target_values]
print(output_index)

一种有效的方法是循环过滤列表。这意味着您应该使用filter()方法来过滤列表。这样,for循环只循环确定的值,而不循环不必要的值。您甚至不必担心valueindex错误,因为您只循环您感兴趣的值。

target_values = [0,0.001,0.002,0.003,..., 0.01]
lst = [0,0.0005,0.001, 0.0015, 0.002,..., 0.1]
output_index = [lst.index(value) for value in filter(lambda x: x in lst, target_values)]
print(output_index)

最新更新