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

如何在嵌套列表推导式中让else不生成空值,仅保留符合条件的结果?

Fixing the List Comprehension to Avoid Empty Strings

Got it, the issue with your current list comprehension is that it generates a value for every single item in the Outer London list—even those that don’t match either the pleasant or royal sounding criteria, which end up as empty strings. Here’s how to adjust it to only keep the results you want:

Solution 1: Filter First in the List Comprehension

We can add a filtering condition at the end of the comprehension to exclude items that don’t meet either criteria, so only matching items get processed into your desired strings:

pleasant_sounding = ['Farm', 'Park', 'Hill', 'Green']
royal_sounding = ['Royal', 'Queen', 'King']
location_dict = {'Outer London': ['Brent Park', 'Woodford', 'Dollis Hill', 'Park Royal', 'Redbridge']}

filtered_results = [
    f"{name} sounds pleasant" if any(x in name for x in pleasant_sounding)
    else f"{name} sounds grand"
    for name in location_dict['Outer London']
    # Only keep items that match at least one criteria
    if any(x in name for x in pleasant_sounding) or any(y in name for y in royal_sounding)
]

print(filtered_results)

Output:

['Brent Park sounds pleasant', 'Dollis Hill sounds pleasant', 'Park Royal sounds grand']

Solution 2: More Efficient Loop (Avoids Duplicate Checks)

The above comprehension works, but it runs the any() checks twice for matching items. For larger datasets, a regular loop is more efficient because we only check each condition once per item:

pleasant_sounding = ['Farm', 'Park', 'Hill', 'Green']
royal_sounding = ['Royal', 'Queen', 'King']
location_dict = {'Outer London': ['Brent Park', 'Woodford', 'Dollis Hill', 'Park Royal', 'Redbridge']}

filtered_results = []
for name in location_dict['Outer London']:
    is_pleasant = any(x in name for x in pleasant_sounding)
    is_royal = any(y in name for y in royal_sounding)
    
    if is_pleasant:
        filtered_results.append(f"{name} sounds pleasant")
    elif is_royal:
        filtered_results.append(f"{name} sounds grand")

print(filtered_results)

This gives the exact same output, but cuts down on redundant computations.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:52:48