如何使用用户输入搜索列表?

时间:2014-02-17 20:45:47

标签: python list indexing

到目前为止,我有......

    def main():
        list = [8, 25, 10, 99, 54, 3, 61, 24]
        print("Your list is: ",list)
        new = input("Please choose a number from the list:")
        print("Your numbers index is:", list.index(new))
        input("Press enter to close program")

所以我的问题是我无法弄清楚如何获取用户输入并获取用户选择的索引。例如,如果用户输入99,我的程序将返回“您的数字索引为:3”

请帮忙。

2 个答案:

答案 0 :(得分:0)

input函数返回一个字符串,而您的列表包含整数。您需要将字符串转换为int:

new = int(input("Please choose a number from the list: "))

答案 1 :(得分:0)

我仔细检查了以下代码。你能尝试一下吗?

def main():
    list = [8, 25, 10, 99, 54, 3, 61, 24]
    print("Your list is: ", list)
    new = int(input("Please choose a number from the list:"))
    print("Your numbers index is:", list.index(new))
    input("Press enter to close program")

main()
相关问题