简体   繁体   English

Python 3.x 列表推导 VS 元组生成器

[英]Python 3.x list comprehension VS tuple generator

Is there any reason for memory, speed or whatever, that I would want to use:是否有任何我想使用的内存、速度或其他原因:

tuple(i for i in range(5000))

instead of:代替:

[i for i in range(5000)]

If I didn't mind the immutability of tuples如果我不介意元组的不变性

Basically a list comprehension is faster than a generator expression and as the reason is that its iteration performs in C (Read the @Veedrac's comment for the reason).基本上,列表理解比生成器表达式更快,原因是 它的迭代在 C 中执行 (阅读@Veedrac 的评论了解原因)。 But the only reason that should use a generator expression within tuple is that you want to perform some operations on your items and/or filter them and more importantly you want a tuple (because of the immutability and its benefits against mutable objects).但是应该在元组中使用生成器表达式的唯一原因是您想对您的项目执行一些操作和/或过滤它们,更重要的是您想要一个元组(因为不变性及其对可变对象的好处)。

After all you can always timeit your code:毕竟,您可以随时对代码进行timeit

In [10]: %timeit tuple(i for i in range(5000))
1000 loops, best of 3: 325 µs per loop

In [11]: %timeit [i for i in range(5000)]
1000 loops, best of 3: 199 µs per loop

Also note that as I mentioned, if you want to use comprehensions you must needed to perform an operation on your items otherwise you can call the function directly on your iterator, which is faster:另请注意,正如我所提到的,如果您想使用推导式,您必须对您的项目执行操作,否则您可以直接在迭代器上调用该函数,这会更快:

In [12]: %timeit list(range(5000))
10000 loops, best of 3: 98.3 µs per loop

Generator expressions (or genexps , for short) are best used in loops to save memory when handling a lot of data.生成器表达式(或简称genexps )最好在循环中使用,以在处理大量数据时节省内存。 It's not considered good practice to expand a genexp to an interable data type (such as a list, tuple, set).将 genexp 扩展为可交互的数据类型(例如列表、元组、集合)并不是一种好的做法。

Also keep in mind that range() in Python 3 is like xrange() in Python 2. It returns a generator.还要记住,Python 3 中的 range() 类似于 Python 2 中的 xrange()。它返回一个生成器。 In fact, xrange() tends to be faster even for 5000. Note: xrange() does not exist in Python 3.事实上,即使是 5000,xrange() 也往往更快。 注意:xrange() 在 Python 3 中不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM