如何用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
相关产品推荐
相关产品推荐

