Python.如何让这个函数返回一个整数而不是一个列表?

该函数接受一个字符串输入,去除标点符号,计算每个单词中的字母数,并返回原始字符串中最短单词的字母数。但是,它将答案作为列表返回。我需要它以整数形式返回结果。在这个给定的示例中它返回 [2],我需要它返回 2。我应该如何修改此代码?


def find_short(s):

    import string

    string_no_punct = s.strip(string.punctuation) 

    word_lenght_list = list(map(len, string_no_punct.split()))

    word_lenght_list.sort()

    new_list = word_lenght_list[:1]

    return new_list

print(find_short("Tomorrow will be another day!"))


喵喵时光机
浏览 171回答 3
3回答

慕娘9325324

你的问题是word_lenght_list[:1]是一个切片操作,返回一个包含word_lenght_listfrom0到1-1ie的所有元素的列表0,因此您在示例案例中得到一个列表[2]。要获得 中的最小值word_lenght_list,只需使用word_lenght_list[0]。更好的解决方案是跳过sort并直接使用min:def find_short(s):    import string    string_no_punct = s.strip(string.punctuation)     word_length_list = list(map(len, string_no_punct.split()))    new_list = min(word_length_list)    return new_list

POPMUISE

您的新代码应如下所示:def find_short(s):     import string    string_no_punct = s.strip(string.punctuation)     word_lenght_list = list(map(len, string_no_punct.split()))     word_lenght_list.sort()     new_list = word_lenght_list[:1]     return new_list[0] print(find_short("Tomorrow will be another day!"))只需更改return new_list为return new_list[0]

哔哔one

在您的代码中new_list = word_lenght_list[:1]这个 [:1] 是一个切片符号。当你对一个列表进行切片时,它会返回一个列表,当你对一个字符串进行切片时,它会返回一个字符串。这就是为什么你得到 list 而不是 int
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python