3 回答
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
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
添加回答
举报
