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

Python实现筛选相同元音单词的函数问题求助

Python单词元音种类匹配函数实现

需求明确

实现word_list函数,接收小写单词列表,返回所有与列表首个单词元音种类完全相同的单词——只看包含哪些元音(数量多少不影响),元音限定为a、e、i、o、u。

最优实现思路:用集合处理元音种类

集合天生适合处理「元素种类是否一致」的问题,自动去重且比较效率高,还能轻松避免索引错误:

  1. 先处理空列表的边界情况,直接返回空列表,防止取第一个元素时出错
  2. 提取首个单词的元音集合:遍历单词字符,筛选出元音后转成集合(自动去重,只保留种类)
  3. 遍历列表中每个单词,生成对应元音集合,和首个单词的集合对比,相等则保留

完整代码实现

def word_list(words):
    # 处理空列表的边界情况,避免索引错误
    if not words:
        return []
    
    # 定义元音集合
    vowels = {'a', 'e', 'i', 'o', 'u'}
    # 获取第一个单词的元音种类集合
    target_vowels = set(char for char in words[0] if char in vowels)
    
    # 遍历所有单词,筛选元音种类匹配的
    result = []
    for word in words:
        current_vowels = set(char for char in word if char in vowels)
        if current_vowels == target_vowels:
            result.append(word)
    return result

# 测试用例验证
def test_q3():
    print(word_list(["toe", "ocelot", "maniac"]) == ["toe", "ocelot"])  # True
    print(word_list(["many", "carriage", "emit", "apricot", "aardvark"]) == ["many","aardvark"])  # True
    print(word_list(["hoops", "chuff", "bot", "bottom"]) == ["hoops", "bot", "bottom"])  # True
    print(word_list(["lab", "carriage", "emit", "apricot"]) == ["lab"])  # True

test_q3()

方案优势说明

  • 统计元音数量的思路不适用:需求是种类一致,不是数量一致,比如"toe"和"ocelot"都有o和e,数量不同但符合要求
  • 嵌套循环可以实现,但代码会更繁琐,集合的方式代码简洁,且集合的比较操作时间复杂度更低,效率更高
  • 加入了空列表判断,彻底避免了索引错误问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:13:00