在不使用 python 中的 'len' 函数的情况下查找列表的长度
Finding length of list without using the 'len' function in python
在我的高中作业中,它的一部分是编写一个函数来计算浮点列表中的平均数。我们不能使用 len 之类的东西,所以像 sum(numList)/float(len(numList))
这样的东西对我来说不是一个选择。我花了一个小时研究并绞尽脑汁寻找一种无需使用 len
函数即可找到列表长度的方法,但我一无所获,所以我希望有人告诉我如何去做或成为指出了正确的方向。帮助我堆栈溢出,你是我唯一的希望。 :)
使用循环将列表中的值相加,同时计数:
def average(numList):
total = 0
count = 0
for num in numList:
total += num
count += 1
return total / count
如果可能向您传递了一个空列表,您可能需要先检查该列表,然后 return 预先确定的值(例如 0
),或者引发比 ZeroDivisionError
不做任何检查就会得到
如果您使用 Python 2 并且列表可能全是整数,您应该将 from __future__ import division
放在文件的顶部,或者转换 total
或count
到 float
在进行除法之前(将其中之一初始化为 0.0
也可以)。
不妨展示如何使用 while
循环进行操作,因为这是另一个学习机会。
通常,您不需要在 for
循环中使用计数器变量。然而,在某些情况下,保持计数以及从列表中检索项目是有帮助的,这就是 enumerate() 派上用场的地方。
基本上,下面的解决方案是@Blckknght 的解决方案在内部所做的。
def average(items):
"""
Takes in a list of numbers and finds the average.
"""
if not items:
return 0
# iter() creates an iterator.
# an iterator has gives you the .next()
# method which will return the next item
# in the sequence of items.
it = iter(items)
count = 0
total = 0
while True:
try:
# when there are no more
# items in the list
total += next(it)
# a stop iteration is raised
except StopIteration:
# this gives us an opportunity
# to break out of the infinite loop
break
# since the StopIteration will be raised
# before a value is returned, we don't want
# to increment the counter until after
# a valid value is retrieved
count += 1
# perform the normal average calculation
return total / float(count)
在我的高中作业中,它的一部分是编写一个函数来计算浮点列表中的平均数。我们不能使用 len 之类的东西,所以像 sum(numList)/float(len(numList))
这样的东西对我来说不是一个选择。我花了一个小时研究并绞尽脑汁寻找一种无需使用 len
函数即可找到列表长度的方法,但我一无所获,所以我希望有人告诉我如何去做或成为指出了正确的方向。帮助我堆栈溢出,你是我唯一的希望。 :)
使用循环将列表中的值相加,同时计数:
def average(numList):
total = 0
count = 0
for num in numList:
total += num
count += 1
return total / count
如果可能向您传递了一个空列表,您可能需要先检查该列表,然后 return 预先确定的值(例如 0
),或者引发比 ZeroDivisionError
不做任何检查就会得到
如果您使用 Python 2 并且列表可能全是整数,您应该将 from __future__ import division
放在文件的顶部,或者转换 total
或count
到 float
在进行除法之前(将其中之一初始化为 0.0
也可以)。
不妨展示如何使用 while
循环进行操作,因为这是另一个学习机会。
通常,您不需要在 for
循环中使用计数器变量。然而,在某些情况下,保持计数以及从列表中检索项目是有帮助的,这就是 enumerate() 派上用场的地方。
基本上,下面的解决方案是@Blckknght 的解决方案在内部所做的。
def average(items):
"""
Takes in a list of numbers and finds the average.
"""
if not items:
return 0
# iter() creates an iterator.
# an iterator has gives you the .next()
# method which will return the next item
# in the sequence of items.
it = iter(items)
count = 0
total = 0
while True:
try:
# when there are no more
# items in the list
total += next(it)
# a stop iteration is raised
except StopIteration:
# this gives us an opportunity
# to break out of the infinite loop
break
# since the StopIteration will be raised
# before a value is returned, we don't want
# to increment the counter until after
# a valid value is retrieved
count += 1
# perform the normal average calculation
return total / float(count)