gpt4 book ai didi

Python:计算if条件列表中元素的数量

转载 作者:太空狗 更新时间:2023-10-30 00:39:24 25 4
gpt4 key购买 nike

给定一个整数列表,计算特定范围内有多少元素的最 Pythonic/最佳方法是什么?

我研究并找到了两种方法:

>>> x = [10, 60, 20, 66, 79, 5]
>>> len([i for i in x if 60 < i < 70])
1

或:

>>> x = [10, 60, 20, 66, 79, 5]
>>> sum(1 for i in x if 60 < i < 70)
1

哪种方法使用的时间/内存更少(对于较大的列表),为什么?或者也许另一种方法更好...

最佳答案

在您提供的具体实例中

[i for i in x if 60 < i < 70]

实际上生成了一个全新的列表,然后取其len。反之,

(1 for i in x if 60 < i < 70)

是一个generator expression对其进行 sum

对于足够大的相关项目,第二个版本会更有效率(尤其是在内存方面)。


时间

x = [65] * 9999999

%%time

len([i for i in x if 60 < i < 70])

CPU times: user 724 ms, sys: 44 ms, total: 768 ms
Wall time: 768 ms
Out[7]:
9999999

%%time

sum(1 for i in x if 60 < i < 70)
CPU times: user 592 ms, sys: 0 ns, total: 592 ms
Wall time: 593 ms

关于Python:计算if条件列表中元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35605899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com