python - 给定列表中的索引
问题描述
[11、12、13、14、15、16、17、18、19、20]。在给定的谷列表中找到整数键的索引。
解决方案
看看列表的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() 方法只返回第一次找到的索引!
推荐阅读
- angular - Angular 6:如何根据 mat-nav-list 选定项在单独的部分中呈现注入数据?
- html - 将滑块值从 html 表单导入到烧瓶应用程序
- javascript - jQuery插件功能永远无法实现
- mysql - 如何在 node.js 中对 MySQL 返回的结果进行嵌套
- wpf - 如何获取 LiveCharts LabelPoint 值?
- exe - 如何使脚本在 Windows 中可执行
- angular - 无法使用 Ionic 3 与 EventEmitters 进行组件通信
- php - varchar 的 MySQL 错误顺序
- macos - 在 Mac OSX 上构建包时遇到问题
- sql-server - Excel 公式转换为 SQL