亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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條經驗 獲得超4個贊

你的問題是


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 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號