Python:Python 列表是为 len() 计数还是为每次调用计数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/699177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:40:31  来源:igfitidea点击:

Python: Do Python Lists keep a count for len() or does it count for each call?

python

提问by PKKid

If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?

如果我一直在很长的列表中调用 len() ,我是在浪费时间,还是在后台保留一个 int 计数?

回答by Ferdinand Beyer

Don't worry: Of course it saves the count and thus len()on lists is a pretty cheap operation. Same is true for strings, dictionaries and sets, by the way!

别担心:当然它会节省计数,因此len()在列表上是一个非常便宜的操作。顺便说一下,字符串、字典和集合也是如此!

回答by AKX

And one more way to find out how it's done is to look it up on Google Code Searchlook at the source on GitHub, if you don't want to download the source yourself.

了解它是如何完成的另一种方法是 在 Google 代码搜索上查找如果不想自己下载源码,可以查看 GitHub 上的源码。

static Py_ssize_t list_length(PyListObject *a)
{
    return a->ob_size;
}

回答by bignose

Write your program so that it's optimised for clarity and easily maintainable. Is your program clearer with a call to len(foo)? Then do that.

编写您的程序,使其针对清晰和易于维护进行优化。通过调用 ,您的程序是否更清晰len(foo)?然后这样做。

Are you worried about the time taken? Use the timeitmodule in the standard libraryto measurethe time taken, and see whether it is significant in your code.

您是否担心所花的时间?使用timeit标准库中模块衡量花费的时间,看看它在你的代码中是否重要。

You will, like most people, very likely be wrong in your guesses about which parts of your program are slowest. Avoid the temptation to guess, and instead measure it to find out.

与大多数人一样,您很可能会错误地猜测程序的哪些部分最慢。避免猜测的诱惑,而是通过测量来找出答案。

Remember that premature optimisation is the root of all evil, in the words of Donald Knuth. Only focus on the speed of code that you have measuredthe speed of, to know whether the benefit would be worth the cost of changing how it works.

请记住,用唐纳德·克努斯 (Donald Knuth) 的话来说,过早优化是万恶之源。只关注你测量过的代码速度,才能知道改变它的工作方式所带来的好处是否值得。

回答by dF.

The question has been answered (lenis O(1)), but here's how you can check for yourself:

问题已得到解答(len是 O(1)),但您可以通过以下方法自行检查:

$ python -m timeit -s "l = range(10)" "len(l)"
10000000 loops, best of 3: 0.119 usec per loop
$ python -m timeit -s "l = range(1000000)" "len(l)"
10000000 loops, best of 3: 0.131 usec per loop

Yep, not really slower.

是的,并不是真的慢。

回答by Ken

A Python "list" is really a resizeable array, not a linked list, so it stores the size somewhere.

Python“列表”实际上是一个可调整大小的数组,而不是链接列表,因此它将大小存储在某处。

回答by Georg Sch?lly

It has to store the length somewhere, so you aren't counting the number of items every time.

它必须将长度存储在某处,因此您不必每次都计算项目的数量。