为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喵时光机 2022-10-06 15:42:06
该函数接受一个字符串输入,去除标点符号,计算每个单词中的字母数,并返回原始字符串中最短单词的字母数。但是,它将答案作为列表返回。我需要它以整数形式返回结果。在这个给定的示例中它返回 [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_listprint(find_short("Tomorrow will be another day!"))
查看完整描述

3 回答

?
慕娘9325324

TA贡献1783条经验 获得超5个赞

你的问题是


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


查看完整回答
反对 回复 2022-10-06
?
POPMUISE

TA贡献1765条经验 获得超5个赞

您的新代码应如下所示:


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]


查看完整回答
反对 回复 2022-10-06
?
哔哔one

TA贡献1854条经验 获得超8个赞

在您的代码中

new_list = word_lenght_list[:1]

这个 [:1] 是一个切片符号。当你对一个列表进行切片时,它会返回一个列表,当你对一个字符串进行切片时,它会返回一个字符串。这就是为什么你得到 list 而不是 int


查看完整回答
反对 回复 2022-10-06
  • 3 回答
  • 0 关注
  • 151 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号