Python 3.x列表理解VS元组生成器 [英] Python 3.x list comprehension VS tuple generator

查看:78
本文介绍了Python 3.x列表理解VS元组生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何我想使用的内存,速度或其他原因:

tuple(i for i in range(5000))

代替:

[i for i in range(5000)]

如果我不介意元组的不变性

解决方案

基本上,列表理解比生成器表达式快,原因是其迭代在C中执行(请阅读@Veedrac的评论原因).但是,在元组中使用生成器表达式的唯一原因是,您想要对项目执行一些操作和/或过滤它们,更重要的是,您想要元组(因为不可变性及其对可变对象的好处).

毕竟,您始终可以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

还要注意,正如我提到的那样,如果您想使用理解力,则必须对项目执行操作,否则可以直接在迭代器上调用该函数,这会更快:

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

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). 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:

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

这篇关于Python 3.x列表理解VS元组生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆