在列表python中找到最长的单词

时间:2016-03-25 04:32:40

标签: python python-3.x

我试图在非空列表中找到最长的单词。我的函数应该返回最长的单词。如果列表中的元素长度相等,我试图在Unicode排序方面排序最长。例如,我试图返回以下内容:

    >>> highest_word(['a', 'cat', 'sat'])
    'sat'
    >>> highest_word(['saturation', 'of', 'colour'])
    'saturation'
    >>> highest_word(['samIam'])
    'samIam'

到目前为止,我可以让第一个工作,到目前为止这是我的代码:

    def highest_word(wordlist):
    longestWord = ""
    max_len = 0

    for word in wordlist:

        if len(word) > max_len:
            longestWord = len(word)
            longestWord = word
    return longestWord

非常感谢任何形式的帮助。

1 个答案:

答案 0 :(得分:10)

这是一个简单的单线

A

这通过将列表的每个元素映射到包含其长度的元组来工作 和字符串本身。

比较两个元组BA[0] > B[0]时,如果A > BA[0] == B[0]。仅当m.getShowCode() 是考虑的第二个要素时。因此,如果两个字符串的长度相等,则将字符串作为决胜局进行比较。