【问题标题】:How do I return the index of value using a for loop and else statement? [closed]如何使用 for 循环和 else 语句返回值的索引? [关闭]
【发布时间】:2020-08-11 09:08:49
【问题描述】:

// 这个函数返回值的索引,如果没有找到则返回-1

Function Integer findValue(Integer nums[], Integer size, Integer value)
Declare Integer index

For index = 0 To size − 1
   If nums[index] == value Then
      Return index
    Else
Return -1   
   End If
End For
End Function

【问题讨论】:

  • 那应该是 Python 代码吗?
  • 这不是 Python 而是类似 VB 的东西?而且您已经提供了一个函数,您是否要求人们为您将其翻译成 Python?为什么不直接使用nums.index(value)
  • 问题是什么?

标签: python arrays for-loop


【解决方案1】:

在 Python 中,已经有一个内置函数用于列表获取索引list.index。如果在列表中找到,则返回传递的元素的索引

【讨论】:

  • list.index 如果未找到该元素,则不返回 -1。它引发了一个异常。
  • 是的,对不起,我把它和 str.find() 搞混了
猜你喜欢
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
相关资源
最近更新 更多