Giter VIP home page Giter VIP logo

Comments (3)

piglei avatar piglei commented on June 22, 2024 5

你好 @klmjoi

使用“列表表达式”和 “next + 生成器表达式“这两种方法最大的区别在于 何时中断,对于前者来说,无论找没找到,都会遍历完整个列表。而后者在找到第一个元素就会返回。

如果用时间复杂度 O 来度量二者效率:

  • “列表表达式” / “next() + 生成器”
  • 平均:二者均为 O(n)
  • 最好情况下的时间复杂度:O(n) 对比 O(1),要找的东西刚好出现在第一个元素
  • 最差情况下的时间复杂度:O(n) 对比 O(n),要找的东西刚好出现在最后一个元素

如果要对比二者的效率,可以选一个规模稍微大点的 list:

# 构造一个 1 到 999 的列表,找里面第一个可以被 200 整除的数,也就是 200
In [3]: numbers = list(range(1, 1000))

# 使用列表表达式,要搜完整个列表,大概耗费 40 µs
In [4]: %timeit [i for i in numbers if i % 200 == 0][0]
43 µs ± 2.65 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [6]: %timeit [i for i in numbers if i % 200 == 0][0]
40.8 µs ± 1.73 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

### 使用 next,找到第一个就返回,大概耗费 9µs
In [10]: %timeit next((i for i in numbers if i % 200 == 0))
8.61 µs ± 83.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [11]: %timeit next((i for i in numbers if i % 200 == 0))
9.24 µs ± 339 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

为什么你的例子里使用 next() 更慢?主要原因是源列表太短,使用 next() 少做的那几次检索还抵不上多调用一次 next 的开销。

感谢你的留言,我在以后修订文章时会补一些这部分的内容。

from one-python-craftsman.

klmjoi avatar klmjoi commented on June 22, 2024

确实如此,感谢~

from one-python-craftsman.

chfw avatar chfw commented on June 22, 2024

在大数据的情况下,这个数列是以百万个为单位,省的时间就更加明显了。

from one-python-craftsman.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.