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

能否用列表推导式解决LeetCode无败绩选手筛选问题?

用列表推导式实现无败绩选手列表

当然可以用列表推导式实现,你之前的写法问题出在两点:

  • 语法错误:w not l完全不对,判断元素是否在集合/列表里要用not in
  • 逻辑漏洞:直接遍历胜方会得到重复值,而且没先收集所有败方的信息

正确的实现步骤如下:

  1. 先把所有败方提取到集合里(集合的成员查询效率远高于列表):
    all_losers = {lose for win, lose in matches}
    
  2. 用列表推导式结合集合推导式,先对胜方去重,再筛选出从未输过的选手:
    matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]
    all_losers = {lose for win, lose in matches}
    neverLost = [win for win in {win for win, lose in matches} if win not in all_losers]
    
    运行后得到的neverLost是[1, 2, 10],和示例一致。

如果需要和题目要求一样返回升序排列的结果,套个sorted()就行:

neverLost = sorted([win for win in {win for win, lose in matches} if win not in all_losers])

本质上是先通过集合推导式去重所有胜方,再用列表推导式筛选出不在败方集合里的选手,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:55:17