在python中,len(list)有什么作用? [英] In python, what does len(list) do?
问题描述
len(list)
是在每次调用列表时计算列表的长度,还是返回内置计数器的值?
我有一个上下文需要检查列表的长度每次循环,如:
Does len(list)
calculate the length of the list every time it is called, or does it return the value of the built-in counter?
I have a context where I need to check the length of a list every time through a loop, like:
listData = []
for value in ioread():
if len(listData)>=25:
processlistdata()
clearlistdata()
listData.append(value)
我应该在每次迭代中检查len(listData)
,还是应该为该列表的长度设置一个计数器?
Should I check len(listData)
on every iteration, or should I have a counter for the length of the list?
推荐答案
您可能应该知道,如果您担心此操作的性能,会在Python 实际上是动态数组.也就是说,它们没有实现为链接列表,通常您必须遍历"它们以计算其长度(除非存储在标头中).
You should probably be aware, if you're worried about this operation's performance, that "lists" in Python are really dynamic arrays. That is, they're not implemented as linked lists, which you generally have to "walk" to compute a length for (unless stored in a header).
由于他们已经需要存储簿记"信息来处理内存分配,因此长度也被存储.
Since they already need to store "bookkeeping" information to handle memory allocation, the length is stored too.
这篇关于在python中,len(list)有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!