编写一个名为shortest()的函数,在字符串列表中查找最短字符串的长度

2024-06-16 13:37:01 发布

您现在位置:Python中文网/ 问答频道 /正文

编写一个名为shortest()的函数,它在字符串列表中查找最短字符串的长度。 函数shortest()接受一个参数: 1字符串列表,文本列表 函数shortest()应该返回textList中最短字符串的长度。您可以假设textList至少包含一个元素(string)。在

例如,以下程序将输出1

beatleLine = ['I', 'am', 'the', 'walrus']
print(shortest(beatleLine))

我不知道该怎么办:

^{pr2}$

Tags: the函数字符串文本程序元素列表参数
3条回答

我会这样做:

def shortest(textList):
    shortest_string_len=len(textList.pop())
    for text in textList:
        actual_text_len=len(text)
        if actual_text_len < shortest_string_len:
            shortest_string_len=actual_text_len
    return (shortest_string_len)


beatleLine = ['I', 'am', 'the', 'walrus']
print(shortest(beatleLine))

使用lambdas非常简单:

shortest = lambda strings: len(min(strings, key = len))

这是最具Python风格的版本:

def shortest_length(textlist):
    return min(len(i) for i in textlist)

虽然在这里map也很漂亮:

^{pr2}$

相关问题 更多 >