Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:在一定条件下从列表(序列)中获取项目数_Python_List_Count_Functional Programming_Sequence - Fatal编程技术网

python:在一定条件下从列表(序列)中获取项目数

python:在一定条件下从列表(序列)中获取项目数,python,list,count,functional-programming,sequence,Python,List,Count,Functional Programming,Sequence,假设我有一个包含大量项目的列表 l = [ 1, 4, 6, 30, 2, ... ] 我想从列表中获取项目的数量,其中一个项目应该满足某些条件。我的第一个想法是: count = len([i for i in l if my_condition(l)]) 但是如果my_condition()筛选列表也有大量项,我认为 为筛选结果创建新列表只是浪费内存。就效率而言,IMHO,上述要求不可能比: count = 0 for i in l: if my_condition(l):

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

l = [ 1, 4, 6, 30, 2, ... ]
我想从列表中获取项目的数量,其中一个项目应该满足某些条件。我的第一个想法是:

count = len([i for i in l if my_condition(l)])
但是如果my_condition()筛选列表也有大量项,我认为 为筛选结果创建新列表只是浪费内存。就效率而言,IMHO,上述要求不可能比:

count = 0
for i in l:
    if my_condition(l):
        count += 1
是否有任何功能风格的方法可以实现在不生成临时列表的情况下获取满足特定条件的项目的#数量

提前谢谢

您想要的是一个列表,而不是一个列表

比如说,

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
这种技术最酷的地方在于,您可以在代码中指定概念上独立的步骤,而无需强制求值并在内存中存储,直到最终结果被求值为止。

您可以使用:

甚至

>>> sum(i % 4 == 3 for i in l)
2
它使用
int(True)==1
这一事实

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


你可以这样做:

l = [1,2,3,4,5,..]
count = sum(1 for i in l if my_condition(i))

它只为满足条件的每个元素添加1。

如果您更喜欢函数式编程,也可以使用
reduce
进行此操作

reduce(lambda count, i: count + my_condition(i), l, 0)

这样,您只需通过一次,不会生成中间列表

@mgilson:我认为它从来没有做过那种计算--
start
默认为0,所以第一个加法是
True+0
,不是吗?是的。也许我应该更清楚。。。
int(True)
是什么并不重要
int(“1”)==1
,但这并不意味着您可以执行
“1”+0
。重要的是python如何计算
integer+True
integer+False
@mgilson:hmm,好吧,你已经说服了我。关键是
bool
int
的子类,你可以轻松地添加bool和int(其中
True
的值为1,
False
的值为0)。那么,这就是我提到的
int(True)==1
,但你的
int(“1”)==1
证明了用这种方式缩写它可能意味着不真实的事情。生成器和列表之间的选择是执行时间和内存消耗之间的选择。如果您对代码进行分析,您会惊讶地发现结果往往是违反直觉的。过早优化是万恶之源。
imap
不适用于当前的Python。
>>> def my_condition(x):
...     return x % 4 == 3
... 
>>> sum(map(my_condition, l))
2
from itertools import imap
sum(imap(my_condition, l))
l = [1,2,3,4,5,..]
count = sum(1 for i in l if my_condition(i))
reduce(lambda count, i: count + my_condition(i), l, 0)