python:在特定条件下从列表(序列)中获取项目数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15375093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python: get number of items from list(sequence) with certain condition
提问by cinsk
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:
但是如果 my_condition() 过滤列表也有大量项目,我认为为过滤结果创建新列表只是浪费内存。为了效率,恕我直言,上面的电话不能比:
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.
提前致谢。
回答by JohnJ
You want a generator comprehensionrather than a list here.
你想要一个生成器理解而不是这里的列表。
For example,
例如,
l = [1, 4, 6, 7, 30, 2]
def my_condition(x):
return x > 5 and x < 20
print sum(1 for x in l if my_condition(x))
# -> 2
print sum(1 for x in range(1000000) if my_condition(x))
# -> 14
Or use itertools.imap(though I think the explicit list and generator expressions look somewhat more Pythonic).
或者使用itertools.imap(尽管我认为显式列表和生成器表达式看起来更像 Pythonic)。
Note that, though it's not obvious from the sumexample, you can compose generator comprehensions nicely. For example,
请注意,虽然从sum示例中并不明显,但您可以很好地组合生成器推导式。例如,
inputs = xrange(1000000) # In Python 3 and above, use range instead of xrange
odds = (x for x in inputs if x % 2) # Pick odd numbers
sq_inc = (x**2 + 1 for x in odds) # Square and add one
print sum(x/2 for x in sq_inc) # Actually evaluate each one
# -> 83333333333500000
The cool thing about this technique is that you can specify conceptually separate steps in code without forcing evaluation and storage in memory until the final result is evaluated.
这种技术很酷的一点是,您可以在代码中在概念上指定单独的步骤,而无需强制计算和存储在内存中,直到计算出最终结果。
回答by DSM
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.
它使用的事实是int(True) == 1.
Alternatively, you could use itertools.imap(python 2) or simply map(python 3):
或者,您可以使用itertools.imap(python 2) 或简单地map(python 3):
>>> def my_condition(x):
... return x % 4 == 3
...
>>> sum(map(my_condition, l))
2
回答by kkonrad
from itertools import imap
sum(imap(my_condition, l))
回答by Jsdodgers
you could do something like:
你可以这样做:
l = [1,2,3,4,5,..]
count = sum(1 for i in l if my_condition(i))
which just adds 1 for each element that satisfies the condition.
它只是为每个满足条件的元素加 1。
回答by Fermat's Little Student
This can also be done using reduceif you prefer functional programming
reduce如果您更喜欢函数式编程,也可以使用
reduce(lambda count, i: count + my_condition(i), l, 0)
This way you only do 1 pass and no intermediate list is generated.
这样您只需执行 1 次传递,而不会生成中间列表。

