3 回答

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

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]

TA貢獻1854條經驗 獲得超8個贊
在您的代碼中
new_list = word_lenght_list[:1]
這個 [:1] 是一個切片符號。當你對一個列表進行切片時,它會返回一個列表,當你對一個字符串進行切片時,它會返回一個字符串。這就是為什么你得到 list 而不是 int
添加回答
舉報