You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python的filter与map函数后得到空列表的原因排查

Why Your Filter/Map Code Returns an Empty List

Hey there! Let's break down why your code is ending up with an empty list, and fix it step by step.

The Root Cause

First, let's zero in on the critical mistake in your code:

b = filter(even, a)
print(list(b))  # This line drains the iterator completely
c = map(cube, b)
print(list(c))  # Now b has no elements left to process!

In Python, filter() returns an iterator—not a static list. Iterators are one-time-use objects: once you traverse them (like converting to a list with list(b)), they're empty forever. When you later pass b to map(), there's nothing left to work with, hence the empty final list.

Fix 1: Avoid Exhausting the Iterator Early

If you don't need to print the filtered values first, skip converting b to a list until after you've used it with map():

# Program to map and filter to make a list whose elements are cubes of even numbers
def even(num):
    # Explicitly return a boolean (non-zero values work, but this makes your intent clearer)
    return num % 2 == 0

def cube(num):
    return num ** 3

a = range(1, 10)
print(list(a))  # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

b = filter(even, a)
c = map(cube, b)
print(list(c))  # Output: [8, 64, 216, 512]

Fix 2: Convert Filter Result to a Reusable List

If you want to inspect the filtered values before mapping, convert b to a list right away. Lists are reusable, unlike iterators:

b = list(filter(even, a))
print(b)  # Output: [2, 4, 6, 8]
c = map(cube, b)
print(list(c))  # Output: [8, 64, 216, 512]

Bonus: Simplify with Lambda Expressions

You can streamline your code even further by using lambda functions instead of defining separate even and cube functions:

a = range(1, 10)
cubes_of_evens = list(map(lambda x: x**3, filter(lambda x: x%2 == 0, a)))
print(cubes_of_evens)  # Output: [8, 64, 216, 512]

内容的提问来源于stack exchange,提问作者Shahbaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:51:18