【问题标题】:What's the best way to call a list that has been created by 'range'?调用“范围”创建的列表的最佳方法是什么?
【发布时间】:2019-09-30 20:44:26
【问题描述】:

我想在 def fibonnaci() 函数下引用 listNum,但出现以下错误:TypeError: 'range' object is not callable。如何解决这个问题?

count = 0
fibC = 1
def fibonnaci():
    listNum = range(1,400)

    listFib = list()
    for num in listNum:
        number =  listNum(num - 1) + listNum(num - 2)
        listFib.append(number)
    return listFib

def numberOfFibonnaci(numbers):
    fibonnaci()
    while count < numbers:
        print(listFib[fibC+i])
        count += 1
        i += 1

def main():
    askF = input("Enter number of Fibonnaci")
    numberOfFibonnaci(askF)

main()

期望引用指定整数之前的整数,并在该整数之前的列表中添加两个空格。

相反,得到这个错误:TypeError: 'range' object is not callable。

【问题讨论】:

  • 你的意思是listNum[num - 1] + listNum[num - 2]?

标签: python python-3.x


【解决方案1】:

您需要通过索引访问listNum的项目,使用方括号[]:

count = 0
fibC = 1


def fibonnaci():
    listNum = range(1, 400)

    listFib = list()
    for num in listNum:
        number = listNum[num - 1] + listNum[num - 2]  # you need to access by index!
        listFib.append(number)
    return listFib


def numberOfFibonnaci(numbers):
    listFib = fibonnaci()
    i = 0
    while i < numbers:
        print(listFib[fibC + i])
        i += 1


def main():
    askF = input("Enter number of Fibonnaci")
    numberOfFibonnaci(int(askF))

main()

输出:

Enter number of Fibonnaci12
3
5
7
9
11
13
15
17
19
21
23
25

【讨论】:

    【解决方案2】:

    Range 用于为您的循环创建一个迭代器,因此您不能尝试调用它。如果您想要一个范围内的数字列表,您可以尝试使用列表推导。它看起来像:

    listNum = [i for i in range(1,400)] 其中 listNum 成为一个列表,其中包含从 1 到 399 的条目

    文档:https://docs.python.org/3/tutorial/datastructures.html

    【讨论】:

    • 你不需要列表理解但是listNum = list(range(1,400))
    • 我相信你使用这两种方法会得到同样的结果。
    • 是的,这两种方法都可以得到相同的结果,但list() 写起来更短,代码更易读。
    • 确实如此!谢谢你的提示!
    猜你喜欢
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多