python:从列表(序列)中获取项目数,具有一定条件 [英] python: get number of items from list(sequence) with certain condition
问题描述
假设我有一个包含大量项目的列表。
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)])
但是如果my_condition()过滤的列表也有很多项目,我认为
创建新列表过滤结果只是浪费内存。为了效率,IMHO,上面的调用不能比:
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?
提前感谢。
推荐答案
您可以使用生成器表达式:
>>> 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) / code>(python 3):
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屋!