首页 > 解决方案 > 给定列表中的索引

问题描述

[11、12、13、14、15、16、17、18、19、20]。在给定的谷列表中找到整数键的索引。

标签: pythonpython-3.xpython-2.7

解决方案


看看列表的index()函数:)

编辑:您描述的功能可能是这样实现的:

def create_valley_list(input_list, cut_index):
    # make sure list is sorted
    sorted_list = sorted(input_list)

    # cut list at given index
    list_before_cut_index = sorted_list[:cut_index + 1]
    list_after_cut_index = sorted_list[cut_index + 1:]

    # reverse left part
    list_before_cut_index.reverse()

    # return joined list
    return list_before_cut_index + sorted_list[cut_index:]

之后,您可以在列表中使用此功能。对于您的示例,这将是:

input_list = [1, 2, 3, 4, 6, 7, 8, 11, 13, 14, 15, 16, 17]

valley_list = create_valley_list(input_list, 8)

现在您可以使用 index() 方法获取列表中任何项目的索引。

print(valley_list.index(8))

返回 2。

但请注意,只有在列表中没有任何项目两次时,这才可靠地工作,因为 index() 方法只返回第一次找到的索引!


推荐阅读