开发者

Efficiently computing size of filtered list

I would like to efficiently compute the size of a filtered list, i.e., I don't want to keep the whole filtered list in memory, I just want to get its size. Is there a more "pythonic" way than computing the size using a for-loop?

For example:

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

UPDATE

Apologies if I was not clear. Although the first list (e.g., my_list) is already in memory, I don't want to create an extra list containing the filtered elements just to count them. I knew about generators and sum but just did not connect the dots... Thanks for your answers.


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


size_of_filtered_list = sum(item%2==0 for item in my_list)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜