列表理解比for循环有什么优势? [英] What is the advantage of a list comprehension over a for loop?

查看:76
本文介绍了列表理解比for循环有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中的for循环上使用列表理解有什么优势? /p>

主要是为了使其更具可读性,还是有其他原因使用列表推导而不是循环?

解决方案

列表理解比构建列表的显式for循环更紧凑:

def slower():
    result = []
    for elem in some_iterable:
        result.append(elem)
    return result

def faster():
    return [elem for elem in some_iterable]

这是因为在list上调用.append()会导致列表对象增长(以块为单位),从而分别为新元素腾出空间,而列表推导会首先创建所有元素,然后再创建list来适应一口气的元素:

>>> some_iterable = range(1000)
>>> import timeit
>>> timeit.timeit('f()', 'from __main__ import slower as f', number=10000)
1.4456570148468018
>>> timeit.timeit('f()', 'from __main__ import faster as f', number=10000)
0.49323201179504395

但是,这并不意味着您应该开始对所有内容使用列表推导!列表理解仍会构建列表对象;如果您使用列表理解只是因为它给您带来了单行循环,请再考虑一下.您可能在浪费时间来构建列表对象,然后再次将其丢弃.在这种情况下,只需坚持正常的for循环即可.

What is the advantage of using a list comprehension over a for loop in Python?

Is it mainly to make it more humanly readable, or are there other reasons to use a list comprehension instead of a loop?

解决方案

List comprehensions are more compact and faster than an explicit for loop building a list:

def slower():
    result = []
    for elem in some_iterable:
        result.append(elem)
    return result

def faster():
    return [elem for elem in some_iterable]

This is because calling .append() on a list causes the list object to grow (in chunks) to make space for new elements individually, while the list comprehension gathers all elements first before creating the list to fit the elements in one go:

>>> some_iterable = range(1000)
>>> import timeit
>>> timeit.timeit('f()', 'from __main__ import slower as f', number=10000)
1.4456570148468018
>>> timeit.timeit('f()', 'from __main__ import faster as f', number=10000)
0.49323201179504395

However, this does not mean you should start using list comprehensions for everything! A list comprehension will still build a list object; if you are using a list comprehension just because it gives you a one-line loop, think again. You are probably wasting cycles building a list object that you then discard again. Just stick to a normal for loop in that case.

这篇关于列表理解比for循环有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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