2010-10-20 58 views
1

我想高效地計算過濾列表的大小,即我不想將整個過濾列表保留在內存中,我只想獲得它的大小。有沒有比使用for循環計算大小更「pythonic」的方法?高效計算過濾列表的大小

例如:

my_list = [1,2,3,4] 

# this loads the entire **filtered** list in memory 
size_of_filtered_list = len([item for item in my_list if item % 2 == 0]) 

# is there a more pythonic way than this? 
size_of_filtered_list = 0 
for item in my_list: 
    if item % 2 == 0: 
     size_of_filtered_list += 1 

更新,如果

道歉我並不清楚。儘管第一個列表(例如my_list)已經在內存中,但我不想創建包含過濾元素的額外列表來計算它們。我知道發電機和總和,但只是沒有連接點...感謝您的答案。

+1

「這加載整個列表在內存中,我相信」?所有列表始終在內存中。重點是什麼? – 2010-10-20 10:48:21

+1

看起來像'量化'。 http://docs.python.org/library/itertools.html#recipes – kennytm 2010-10-20 10:51:59

+1

@ S.Lott:我認爲他的意思是說,如果他創建了這個列表,請參閱他的「for循環」。 – 2010-10-20 11:00:20

回答

6
size_of_filtered_list = sum(1 for item in my_list if item % 2 == 0) 
2
size_of_filtered_list = sum(item%2==0 for item in my_list) 
+0

創建列表不是嗎? – SilentGhost 2010-10-20 10:38:40

+0

@SilentGhost:不,它不是生成器表達式是惰性的,但是gnibbler的解決方案會稍微快一點,因爲它既懶惰又sum()不需要添加零。 – 2010-10-20 10:56:58

+0

@Lie:你在這裏似乎並不新鮮,但[無論如何](http://stackoverflow.com/posts/3976880/revisions) – SilentGhost 2010-10-20 10:58:17