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

Python 如何让这个函数返回一个整数而不是一个列表?,python,Python,此函数接受字符串输入,删除标点符号,计算每个单词中的字母数,并返回原始字符串中最短单词的字母数。但是,它会以列表的形式返回答案。我需要它以整数形式返回结果。在这个给定的示例中,它返回[2],我需要它返回2。我应该如何修改此代码 def find_short(s): import string string_no_punct = s.strip(string.punctuation) word_lenght_list = list(map(len, string_no_p

此函数接受字符串输入,删除标点符号,计算每个单词中的字母数,并返回原始字符串中最短单词的字母数。但是,它会以列表的形式返回答案。我需要它以整数形式返回结果。在这个给定的示例中,它返回[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!"))

您的新代码应该如下所示:

def find_short(s):
导入字符串
string\u no\u punct=s.strip(string.标点符号)
word\u lenght\u list=list(映射(len,string\u no\u punt.split())
单词长度列表。排序()
新列表=单词长度列表[:1]
返回新的_列表[0]
打印(查找_short(“明天将是新的一天!”)

只需将代码中的
返回新列表
更改为
返回新列表[0]

new_list = word_lenght_list[:1]
这个[:1]是一个切片表示法。当你切片一个列表时,它返回一个列表,当你切片一个字符串时,它返回一个字符串。这就是为什么你得到的是列表而不是int

你的问题是

word_lenght_list[:1]
是一种切片操作,返回一个包含
word\u lenght\u list
所有元素的列表,从
0
1-1
,即
0
,因此在您的示例中可以得到一个列表
[2]
。要获得
word\u lenght\u列表中的最小值,只需使用
word\u lenght\u列表[0]

更好的解决方案是跳过
排序
,只使用
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

返回新列表[0]
或使用
new\u list=word\u lengh\u list[0]
获取一个
int
以开始感谢Nick。我想选择您的答案作为正确答案,但我不能这样做,因为它是一个注释。return int(new_list[0])或只是return new_list[0]。。。这应该是一个评论。关于列表的任何教程都会介绍如何访问列表元素。请记住,这是一个为专业和热心程序员提供有用答案的档案。。。不是“帮助站点”。我很高兴你的问题得到了解决,但这并不是要添加到我们的数据库中的东西。首先,我为奇怪的格式问题感到抱歉,我在手机上,它似乎不喜欢复制/粘贴