[英]What's the best way to call a list that has been created by 'range'?
I want to reference listNum under def fibonnaci() function, but I am getting the following error: TypeError: 'range' object is not callable.我想在 def fibonnaci() function 下引用 listNum,但出现以下错误:TypeError: 'range' object is not callable。 How to fix this problem?如何解决这个问题?
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()
Expect to reference the integer before the designated one and add to the integer two spaces in a list before it.期望在指定之前引用 integer 并在 integer 之前的列表中添加两个空格。
Instead, get this error: TypeError: 'range' object is not callable.相反,得到这个错误: TypeError: 'range' object is not callable。
You need to access the items of listNum by index, using square brackets []
:您需要使用方括号[]
按索引访问 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()
Outputs:输出:
Enter number of Fibonnaci12
3
5
7
9
11
13
15
17
19
21
23
25
Range is used to create an iterator for your loops, so you can not try to call it. Range 用于为您的循环创建一个迭代器,因此您不能尝试调用它。 If you want a list of numbers within a range, you can try using a list comprehension.如果您想要一个范围内的数字列表,您可以尝试使用列表推导。 It would look something like:它看起来像:
listNum = [i for i in range(1,400)]
where listNum becomes a list containing entries from 1 to 399 listNum = [i for i in range(1,400)]
其中 listNum 成为一个列表,其中包含从 1 到 399 的条目
documentation: https://docs.python.org/3/tutorial/datastructures.html文档: https://docs.python.org/3/tutorial/datastructures.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.