python:在特定条件下从列表(序列)中获取项目数 [英] python: get number of items from list(sequence) with certain condition

查看:27
本文介绍了python:在特定条件下从列表(序列)中获取项目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含大量项目的列表.

l = [ 1, 4, 6, 30, 2, ... ]

我想从该列表中获取项目数,其中项目应满足特定条件.我的第一个想法是:

count = len([i for i in l if my_condition(l)])

但是如果 my_condition() 过滤列表也有很多项目,我认为为过滤结果创建新列表只是浪费内存.为了效率,恕我直言,上面的电话不能比:

count = 0对于我在 l:如果 my_condition(l):计数 += 1

有没有什么函数式的方法可以实现在不生成临时列表的情况下获取满足特定条件的项目数?

提前致谢.

解决方案

您可以使用 生成器表达:

<预><代码>>>>l = [1, 3, 7, 2, 6, 8, 10]>>>sum(1 for i in l if i % 4 == 3)2

甚至

<预><代码>>>>sum(i % 4 == 3 for i in l)2

它使用了 int(True) == 1 的事实.

或者,您可以使用 itertools.imap (python 2) 或简单地使用 map (python 3):

<预><代码>>>>def my_condition(x):...返回 x % 4 == 3...>>>总和(地图(my_condition,l))2

Assuming that I have a list with huge number of items.

l = [ 1, 4, 6, 30, 2, ... ]

I want to get the number of items from that list, where an item should satisfy certain condition. My first thought was:

count = len([i for i in l if my_condition(l)])

But if the my_condition() filtered list has also great number of items, I think that creating new list for filtered result is just waste of memory. For efficiency, IMHO, above call can't be better than:

count = 0
for i in l:
    if my_condition(l):
        count += 1

Is there any functional-style way to achieve to get the # of items that satisfy certain condition without generating temporary list?

Thanks in advance.

解决方案

You can use a generator expression:

>>> l = [1, 3, 7, 2, 6, 8, 10]
>>> sum(1 for i in l if i % 4 == 3)
2

or even

>>> sum(i % 4 == 3 for i in l)
2

which uses the fact that int(True) == 1.

Alternatively, you could use itertools.imap (python 2) or simply map (python 3):

>>> def my_condition(x):
...     return x % 4 == 3
... 
>>> sum(map(my_condition, l))
2

这篇关于python:在特定条件下从列表(序列)中获取项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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