【问题标题】:Returning index value of element from list of integers从整数列表中返回元素的索引值
【发布时间】:2019-05-20 14:38:39
【问题描述】:

python新手所以容易出错,我的问题是:

一个排序好的整数数组被旋转了未知的次数。

给定这样一个数组,以比线性时间更快的速度找到数组中元素的索引。如果数组中不存在该元素,则返回null。

例如,给定数组 [13, 18, 25, 2, 8, 10] 和元素 8,返回 4(数组中 8 的索引值)。

您可以假设数组中的所有整数都是唯一的。

我已经尝试过的代码:

def find_index(x, a):
    x = input("Enter number wish to be found:  ")
    a = [13, 18, 25, 2, 8, 10]
    for element in a:
        if x not in a:
            return None
        else:
            print(a.index(x))

print(find_index())

我希望能够让用户输入一个数字,并接收返回索引位置的值或None。我碰到了一堵砖墙,不知道从哪里继续。有什么想法吗?

编辑:我将错误与另一个错误混淆了。真正给出的错误是:find_index() missing 2 required positional arguments: 'x' and 'a'

【问题讨论】:

  • 该代码给出了不同的错误:TypeError: find_index() missing 2 required positional arguments: 'x' and 'a'。请发minimal reproducible example

标签: python python-3.x list indexing


【解决方案1】:
  1. 您提供的代码不会产生上述错误。

  2. 为什么函数接受 2 个参数,然后立即覆盖它们?

  3. input 返回一个字符串。您必须将 x 转换为整数。

无论如何,循环没有任何意义。您需要做的所有功能就是包装.index

def find_index():
    try:
        x = int(input("Enter number wish to be found:  "))
    except ValueError:
        return 'You have to input an integer'
    a = [13, 18, 25, 2, 8, 10]
    try:
        return a.index(x)
    except ValueError:
        return None

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2018-07-09
    • 2018-08-16
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多