Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何让程序只显示最长的单词而不是字符串中的每个单词?_Python_Function - Fatal编程技术网

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")