更改代码以使用列表理解

2024-04-25 23:36:18 发布

您现在位置:Python中文网/ 问答频道 /正文

对Python非常陌生,尝试通过一些在线示例自学。我解决了一个问题,但当我和一个朋友交谈时,他告诉我应该使用列表理解来完成这样的任务。唯一的问题是,我看不出如何使用列表理解而不是生成器函数来实现任务。这是工作的代码,所有的帮助是感激的!你知道吗

#!/usr/bin/python

def find_longest_word(sentence):
    word = sentence.split()
    long_word = max(len(s) for s in word) # [x for x in range]    
    print "The length of the longest word is: ",long_word
    #return
find_longest_word("The quick brown fox jumps over the lazy dog with pneumonia") # For testing

谢谢


Tags: the函数in示例列表forlongest朋友
3条回答

比列表理解更好的方法是使用高阶函数(可以将另一个函数作为参数的函数),例如max。对maxkey参数将应用于sentence.split()中的每个元素,并基于此确定顺序。以下是几个例子:

>>> def find_longest_word(sentence):
...     longest = max(sentence.split(), key=len)
...     print(longest, len(longest))
...
>>> find_longest_word("The quick brown fox jumps over the lazy dog")
quick 5
>>> find_longest_word("The quick brown fox juuuuumps over the lazy dog")
juuuuumps 9
>>>

请注意,len是python的内置函数,用于确定对象的长度。你知道吗

让我们快速讨论一下列表理解。。。你知道吗

让我们用一个普通的for loop像这样:

sentence = 'Hello how are you doing today?'
lengths = []
for word in sentence.split():
    lengths.append(len(word))

这相当于:

[len(word) for word in sentence.split()]

单for循环列表理解的正常语法是[value for value in list] 在这里可以看到for value in list,它与普通for循环相同。唯一的区别是返回的值不是在for循环之后,而是在之前。你知道吗

对于您的情况,您可以这样做:max([len(word) for word in sentence.split()])

列表理解似乎不适合你所寻求的结果。相反,您可以将列表word传递给具有位置参数key的内置函数max():该函数对word中的每个元素进行操作,并返回一个值(在本例中为长度)作为排序值:

len(max(word,key=len))

相关问题 更多 >