Python 如何让程序只显示最长的单词而不是字符串中的每个单词?
该程序将打印每个字旁边的最长的长度,但我只希望它打印最长的字。请帮助。试试这个:Python 如何让程序只显示最长的单词而不是字符串中的每个单词?,python,function,Python,Function,该程序将打印每个字旁边的最长的长度,但我只希望它打印最长的字。请帮助。试试这个: def find_longest_word(string): d = [] a = string.split() for x in a: b = (x.count("") - 1) d.append(b) f = max(d) print (x, f) find_longest_word("hello my name is
def find_longest_word(string):
d = []
a = string.split()
for x in a:
b = (x.count("") - 1)
d.append(b)
f = max(d)
print (x, f)
find_longest_word("hello my name is k")
x.count(“”
返回”
在字符串中显示的次数。假设字符串是“mystring”<代码>“m”不是“
”、“y”
不是“
”、“s”
不是”、,等等。总计数:0。要获取字符串的长度,请使用len(x)
。另外,您使f
等于d
中的最大值,而不是b
。以下是修改后的版本:
def find_longest_word(string):
a = string.split()
f = -1
longest = None
for x in a:
if len(x) > f:
f = len(x)
longest = x
print (longest, f)
>>> find_longest_word("hello my name is k")
('hello', 5)
测试:
输出:
find_longest_word("This is my sentence that has a longest word.")
如果希望它像句子:8
那样打印,请使用打印'{}:{}'。格式(最长)
这里有一个简短的函数来查找句子中最长的单词:
('sentence', 8)
例如:
def find_longest_word(s):
return max([(len(w), w) for w in s.split(" ")])[1]
说明:
这将创建一个具有列表理解和s.split(“”
)的元组列表,然后将单词的长度和单词本身存储在元组中。然后在元组列表上调用max函数,它检索单词长度最长的元组(即第0个元组参数),然后简单地返回单词(即第一个元组参数),并使用…][1]
注意:如果要返回单词的长度和单词本身,只需将函数修改为:返回最大值([(len(w),w)表示s.split中的w(“”))
。这将删除对元组的索引并返回完整元组。一行:
find_longest_word("This is an incredibly long sentence!")
>>> incredibly
使用len
获取Python中字符串的长度,如果不希望它打印一堆单词,请将print
放在循环之外。
find_longest_word("This is an incredibly long sentence!")
>>> incredibly
def longest(s):
return sorted(s.split(), key=len, reverse=True)[0]
print longest("this is a string")