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

如何用Python列表推导式简化获取单词首尾最小字符的函数代码

需求说明

我需要实现如下功能的函数:

def retrieve_smallest_letter(words):
"""
Input: 'words' (lst) which represents a list of strings.
Output: A new list with the smaller letter of the each word's 
          first and last index value compared to be appended to the list.
For Example:
>>> lst = ['sandbox', 'portabello', 'lion', 'australia', 'salamander']
>>> retrieve_smallest_letter(lst)
['s', 'o', 'l', 'a', 'r']
"""
现有实现

我目前写的代码如下:

def retrieve_smallest_letter(words):
    lst = []
    for i in range(len(words)):
        first_word = words[i][0]
        last_word = words[i][len(words[i])-1]
        if first_word < last_word:
            lst.append(str(first_word))
        else:
            lst.append(str(last_word))

    return lst
列表推导式优化方案

你可以直接借助Python内置的min()函数+列表推导式简化代码,简化后的实现如下:

def retrieve_smallest_letter(words):
    return [min(word[0], word[-1]) for word in words]

优化点说明:

  • 直接迭代words列表中的每个字符串元素,无需通过range(len(words))遍历索引,写法更直观
  • 用字符串负索引word[-1]直接取字符串最后一位,替代原有的word[len(word)-1]写法
  • 内置函数min()可以直接返回两个字符中更小的那个,省略了手动写if-else判断的逻辑
  • 整个循环、判断、追加列表的逻辑全部整合到列表推导式中,代码更简洁高效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:57:02